El Plataforma de identidad de Microsoft admite tres tipos de credenciales para autenticar aplicaciones y entidades de servicio: contraseñas (secretos de aplicación), certificados y credenciales de identidad federada. Si no puede usar credenciales de identidad federada para la aplicación, use certificados en lugar de secretos.
Puede agregar o quitar certificados mediante el Centro de administración Microsoft Entra. Sin embargo, es posible que tenga que automatizar la adición de credenciales de certificado para la aplicación o la entidad de servicio.
En este artículo se proporcionan instrucciones para usar scripts de Microsoft Graph y PowerShell para actualizar las credenciales de certificado mediante programación para un registro de aplicaciones.
Requisitos previos
Para completar este tutorial, necesita los siguientes recursos y privilegios:
- Un inquilino de Microsoft Entra activo.
- Un cliente de API como Graph Explorer. Inicie sesión como un usuario con permiso para crear y administrar aplicaciones en el inquilino. Los roles Desarrollador de aplicaciones (de una aplicación de su propiedad) y Administrador de aplicaciones son los roles con menos privilegios que pueden realizar esta operación.
- Certificado firmado que se usará para autenticar la aplicación. En este artículo se usa un certificado autofirmado con fines de demostración. Para generar uno, consulte Creación de un certificado público autofirmado para autenticar la aplicación.
Precaución
Usar certificados a través de secretos; sin embargo, no use certificados autofirmados. Pueden reducir la seguridad de la aplicación debido a diversos factores, como el uso de un hash y conjuntos de cifrado obsoletos o la falta de validación. Obtenga certificados de una entidad de certificación de confianza conocida.
Paso 1: Leer los detalles del certificado
Para agregar un certificado mediante programación mediante Microsoft Graph, necesita la clave del certificado. Opcionalmente, puede agregar la huella digital del certificado.
[Opcional] Obtención de la huella digital del certificado
Opcionalmente, puede agregar la huella digital del certificado a la carga de la solicitud. Para agregar la huella digital, ejecute la siguiente solicitud de PowerShell para leer la huella digital del certificado. En esta solicitud se supone que ha generado y exportado el certificado a la unidad local.
Solicitud
## Replace the file path with the source of your certificate and output path with the location where you want to save the thumprint details
Get-PfxCertificate -Filepath "C:\Users\admin\Desktop\20230112.cer" | Out-File -FilePath "C:\Users\admin\Desktop\20230112.cer.thumbprint.txt"
Respuesta
La salida del archivo .txt puede ser similar al ejemplo siguiente.
Thumbprint Subject
---------- -------
5A126608ED1A1366F714A4A62B7015F3262840F1 CN=20230112
Obtención de la clave de certificado
Para leer la clave del certificado y guardarlo en un archivo .txt mediante PowerShell, ejecute la siguiente solicitud.
Solicitud
PowerShell < 6:
## Replace the file path with the location of your certificate
[convert]::ToBase64String((Get-Content C:\Users\admin\Desktop\20230112.cer -Encoding byte)) | Out-File -FilePath "C:\Users\admin\Desktop\20230112.key.txt"
PowerShell >= 6:
## Replace the file path with the location of your certificate
[convert]::ToBase64String((Get-Content C:\Users\admin\Desktop\20230112.cer -AsByteStream)) | Out-File -FilePath "C:\Users\admin\Desktop\20230112.key.txt"
Respuesta
La salida del archivo .txt puede ser similar al ejemplo siguiente.
Nota: La clave que se muestra aquí se abrevia para mejorar la legibilidad.
MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...dG+7WMIBsIUy0xz6MmyvfSohz3oNP4jHt7pJ9TyxnvDlaxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A==
Paso 2: Agregar los detalles del certificado mediante Microsoft Graph
Solicitud
La siguiente solicitud agrega los detalles del certificado a una aplicación. La configuración es la siguiente:
-
StartDateTime es la fecha en que o después de crear el certificado.
-
EndDateTime puede ser un máximo de un año desde startDateTime. Si no lo especifica, el sistema asigna automáticamente una fecha un año después de startDateTime.
- El tipo y el uso deben ser
AsymmetricX509Cert y Verify, respectivamente.
- Asigne el nombre del firmante del certificado a la propiedad displayName .
- La clave es el valor codificado en Base64 que generó en el paso anterior. La huella digital se incluye en la clave codificada. Al agregar la clave también se agrega la huella digital.
Nota:
Si la aplicación tiene un certificado válido existente que desea seguir usando para la autenticación, incluya los detalles del certificado actual y el nuevo en el objeto keyCredentials de la aplicación. Dado que se trata de una llamada PATCH, que por protocolo reemplaza el contenido de la propiedad por los nuevos valores, incluido solo el nuevo certificado reemplaza los certificados existentes por el nuevo.
En el ejemplo siguiente se agrega un nuevo certificado y se reemplazan los certificados existentes.
Nota: La clave que se muestra aquí se abrevia para mejorar la legibilidad.
PATCH https://graph.microsoft.com/v1.0/applications/bb77f42f-dacb-4ece-b3e6-285e63c24d52
Content-type: application/json
{
"keyCredentials": [
{
"endDateTime": "2024-01-11T15:31:26Z",
"startDateTime": "2023-01-12T15:31:26Z",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"key": "base64MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...laxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A==",
"displayName": "CN=20230112"
}
]
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new Application
{
KeyCredentials = new List<KeyCredential>
{
new KeyCredential
{
EndDateTime = DateTimeOffset.Parse("2024-01-11T15:31:26Z"),
StartDateTime = DateTimeOffset.Parse("2023-01-12T15:31:26Z"),
Type = "AsymmetricX509Cert",
Usage = "Verify",
Key = Convert.FromBase64String("base64MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...laxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A=="),
DisplayName = "CN=20230112",
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications["{application-id}"].PatchAsync(requestBody);
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewApplication()
keyCredential := graphmodels.NewKeyCredential()
endDateTime , err := time.Parse(time.RFC3339, "2024-01-11T15:31:26Z")
keyCredential.SetEndDateTime(&endDateTime)
startDateTime , err := time.Parse(time.RFC3339, "2023-01-12T15:31:26Z")
keyCredential.SetStartDateTime(&startDateTime)
type := "AsymmetricX509Cert"
keyCredential.SetType(&type)
usage := "Verify"
keyCredential.SetUsage(&usage)
key := []byte("base64MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...laxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A==")
keyCredential.SetKey(&key)
displayName := "CN=20230112"
keyCredential.SetDisplayName(&displayName)
keyCredentials := []graphmodels.KeyCredentialable {
keyCredential,
}
requestBody.SetKeyCredentials(keyCredentials)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
applications, err := graphClient.Applications().ByApplicationId("application-id").Patch(context.Background(), requestBody, nil)
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Application application = new Application();
LinkedList<KeyCredential> keyCredentials = new LinkedList<KeyCredential>();
KeyCredential keyCredential = new KeyCredential();
OffsetDateTime endDateTime = OffsetDateTime.parse("2024-01-11T15:31:26Z");
keyCredential.setEndDateTime(endDateTime);
OffsetDateTime startDateTime = OffsetDateTime.parse("2023-01-12T15:31:26Z");
keyCredential.setStartDateTime(startDateTime);
keyCredential.setType("AsymmetricX509Cert");
keyCredential.setUsage("Verify");
byte[] key = Base64.getDecoder().decode("base64MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...laxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A==");
keyCredential.setKey(key);
keyCredential.setDisplayName("CN=20230112");
keyCredentials.add(keyCredential);
application.setKeyCredentials(keyCredentials);
Application result = graphClient.applications().byApplicationId("{application-id}").patch(application);
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
const options = {
authProvider,
};
const client = Client.init(options);
const application = {
keyCredentials: [
{
endDateTime: '2024-01-11T15:31:26Z',
startDateTime: '2023-01-12T15:31:26Z',
type: 'AsymmetricX509Cert',
usage: 'Verify',
key: 'base64MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...laxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A==',
displayName: 'CN=20230112'
}
]
};
await client.api('/applications/bb77f42f-dacb-4ece-b3e6-285e63c24d52')
.update(application);
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\Application;
use Microsoft\Graph\Generated\Models\KeyCredential;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new Application();
$keyCredentialsKeyCredential1 = new KeyCredential();
$keyCredentialsKeyCredential1->setEndDateTime(new \DateTime('2024-01-11T15:31:26Z'));
$keyCredentialsKeyCredential1->setStartDateTime(new \DateTime('2023-01-12T15:31:26Z'));
$keyCredentialsKeyCredential1->setType('AsymmetricX509Cert');
$keyCredentialsKeyCredential1->setUsage('Verify');
$keyCredentialsKeyCredential1->setKey(\GuzzleHttp\Psr7\Utils::streamFor(base64_decode('base64MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...laxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A==')));
$keyCredentialsKeyCredential1->setDisplayName('CN=20230112');
$keyCredentialsArray []= $keyCredentialsKeyCredential1;
$requestBody->setKeyCredentials($keyCredentialsArray);
$result = $graphServiceClient->applications()->byApplicationId('application-id')->patch($requestBody)->wait();
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
Import-Module Microsoft.Graph.Applications
$params = @{
keyCredentials = @(
@{
endDateTime = [System.DateTime]::Parse("2024-01-11T15:31:26Z")
startDateTime = [System.DateTime]::Parse("2023-01-12T15:31:26Z")
type = "AsymmetricX509Cert"
usage = "Verify"
key = [System.Text.Encoding]::ASCII.GetBytes("base64MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...laxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A==")
displayName = "CN=20230112"
}
)
}
Update-MgApplication -ApplicationId $applicationId -BodyParameter $params
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.application import Application
from msgraph.generated.models.key_credential import KeyCredential
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Application(
key_credentials = [
KeyCredential(
end_date_time = "2024-01-11T15:31:26Z",
start_date_time = "2023-01-12T15:31:26Z",
type = "AsymmetricX509Cert",
usage = "Verify",
key = base64.urlsafe_b64decode("base64MIIDADCCAeigAwIBAgIQP6HEGDdZ65xJTcK4dCBvZzANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMjAeFw0yMzAxMTIwODExNTZaFw0yNDAxMTIwODMxNTZaMBMxETAPBgNVBAMMCDIwMjMwMTEyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseKf1weEacJ67D6/...laxQPUbuIL+DaXVkKRm1V3GgIpKTBqMzTf4tCpy7rpUZbhcwAFw6h9A=="),
display_name = "CN=20230112",
),
],
)
result = await graph_client.applications.by_application_id('application-id').patch(request_body)
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
En el ejemplo siguiente se agrega un nuevo certificado sin reemplazar el certificado existente por la huella digital 52ED9B5038A47B9E2E2190715CC238359D4F8F73.
Nota: La clave que se muestra aquí se abrevia para mejorar la legibilidad.
PATCH https://graph.microsoft.com/v1.0/applications/bb77f42f-dacb-4ece-b3e6-285e63c24d52
Content-type: application/json
{
"keyCredentials": [
{
"endDateTime": "2024-01-11T15:31:26Z",
"startDateTime": "2023-01-12T09:31:26Z",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"key": "base64MIIDADCCAeigAwIBAgIQejfrj3S974xI//npv7hFHTANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExNDAeFw0yMzAxMTIwOTA4NThaFw0yNDAxMTIwOTI4NThaMBMxETAPBgNVBAMMCDIwMjMwMTE0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt5vEj6j1l5wOVHR4eDGe77HWslaIVJ1NqxrXPm/...+R+U7sboj+kUvmFzXI+Ge73Liu8egL2NzOHHpO43calWgq36a9YW1yhBQR1ioEchu6jmudW3rF6ktmVqQ==",
"displayName": "CN=20230114"
},
{
"customKeyIdentifier": "52ED9B5038A47B9E2E2190715CC238359D4F8F73",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"key": "base64MIIDADCCAeigAwIBAgIQfoIvchhpToxKEPI4iMrU1TANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMzAeFw0yMzAxMTIwODI3NTJaFw0yNDAxMTIwODQ3NTJaMBMxETAPBgNVBAMMCDIwMjMwMTEzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+iqg1nMjYmFcFJh/.../S5X6qoEOyJBgtfpSBANWAdA==",
"displayName": "CN=20230113"
}
]
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Models;
var requestBody = new Application
{
KeyCredentials = new List<KeyCredential>
{
new KeyCredential
{
EndDateTime = DateTimeOffset.Parse("2024-01-11T15:31:26Z"),
StartDateTime = DateTimeOffset.Parse("2023-01-12T09:31:26Z"),
Type = "AsymmetricX509Cert",
Usage = "Verify",
Key = Convert.FromBase64String("base64MIIDADCCAeigAwIBAgIQejfrj3S974xI//npv7hFHTANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExNDAeFw0yMzAxMTIwOTA4NThaFw0yNDAxMTIwOTI4NThaMBMxETAPBgNVBAMMCDIwMjMwMTE0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt5vEj6j1l5wOVHR4eDGe77HWslaIVJ1NqxrXPm/...+R+U7sboj+kUvmFzXI+Ge73Liu8egL2NzOHHpO43calWgq36a9YW1yhBQR1ioEchu6jmudW3rF6ktmVqQ=="),
DisplayName = "CN=20230114",
},
new KeyCredential
{
CustomKeyIdentifier = Convert.FromBase64String("52ED9B5038A47B9E2E2190715CC238359D4F8F73"),
Type = "AsymmetricX509Cert",
Usage = "Verify",
Key = Convert.FromBase64String("base64MIIDADCCAeigAwIBAgIQfoIvchhpToxKEPI4iMrU1TANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMzAeFw0yMzAxMTIwODI3NTJaFw0yNDAxMTIwODQ3NTJaMBMxETAPBgNVBAMMCDIwMjMwMTEzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+iqg1nMjYmFcFJh/.../S5X6qoEOyJBgtfpSBANWAdA=="),
DisplayName = "CN=20230113",
},
},
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications["{application-id}"].PatchAsync(requestBody);
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphmodels "github.com/microsoftgraph/msgraph-sdk-go/models"
//other-imports
)
requestBody := graphmodels.NewApplication()
keyCredential := graphmodels.NewKeyCredential()
endDateTime , err := time.Parse(time.RFC3339, "2024-01-11T15:31:26Z")
keyCredential.SetEndDateTime(&endDateTime)
startDateTime , err := time.Parse(time.RFC3339, "2023-01-12T09:31:26Z")
keyCredential.SetStartDateTime(&startDateTime)
type := "AsymmetricX509Cert"
keyCredential.SetType(&type)
usage := "Verify"
keyCredential.SetUsage(&usage)
key := []byte("base64MIIDADCCAeigAwIBAgIQejfrj3S974xI//npv7hFHTANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExNDAeFw0yMzAxMTIwOTA4NThaFw0yNDAxMTIwOTI4NThaMBMxETAPBgNVBAMMCDIwMjMwMTE0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt5vEj6j1l5wOVHR4eDGe77HWslaIVJ1NqxrXPm/...+R+U7sboj+kUvmFzXI+Ge73Liu8egL2NzOHHpO43calWgq36a9YW1yhBQR1ioEchu6jmudW3rF6ktmVqQ==")
keyCredential.SetKey(&key)
displayName := "CN=20230114"
keyCredential.SetDisplayName(&displayName)
keyCredential1 := graphmodels.NewKeyCredential()
customKeyIdentifier := []byte("52ED9B5038A47B9E2E2190715CC238359D4F8F73")
keyCredential1.SetCustomKeyIdentifier(&customKeyIdentifier)
type := "AsymmetricX509Cert"
keyCredential1.SetType(&type)
usage := "Verify"
keyCredential1.SetUsage(&usage)
key := []byte("base64MIIDADCCAeigAwIBAgIQfoIvchhpToxKEPI4iMrU1TANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMzAeFw0yMzAxMTIwODI3NTJaFw0yNDAxMTIwODQ3NTJaMBMxETAPBgNVBAMMCDIwMjMwMTEzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+iqg1nMjYmFcFJh/.../S5X6qoEOyJBgtfpSBANWAdA==")
keyCredential1.SetKey(&key)
displayName := "CN=20230113"
keyCredential1.SetDisplayName(&displayName)
keyCredentials := []graphmodels.KeyCredentialable {
keyCredential,
keyCredential1,
}
requestBody.SetKeyCredentials(keyCredentials)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
applications, err := graphClient.Applications().ByApplicationId("application-id").Patch(context.Background(), requestBody, nil)
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
Application application = new Application();
LinkedList<KeyCredential> keyCredentials = new LinkedList<KeyCredential>();
KeyCredential keyCredential = new KeyCredential();
OffsetDateTime endDateTime = OffsetDateTime.parse("2024-01-11T15:31:26Z");
keyCredential.setEndDateTime(endDateTime);
OffsetDateTime startDateTime = OffsetDateTime.parse("2023-01-12T09:31:26Z");
keyCredential.setStartDateTime(startDateTime);
keyCredential.setType("AsymmetricX509Cert");
keyCredential.setUsage("Verify");
byte[] key = Base64.getDecoder().decode("base64MIIDADCCAeigAwIBAgIQejfrj3S974xI//npv7hFHTANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExNDAeFw0yMzAxMTIwOTA4NThaFw0yNDAxMTIwOTI4NThaMBMxETAPBgNVBAMMCDIwMjMwMTE0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt5vEj6j1l5wOVHR4eDGe77HWslaIVJ1NqxrXPm/...+R+U7sboj+kUvmFzXI+Ge73Liu8egL2NzOHHpO43calWgq36a9YW1yhBQR1ioEchu6jmudW3rF6ktmVqQ==");
keyCredential.setKey(key);
keyCredential.setDisplayName("CN=20230114");
keyCredentials.add(keyCredential);
KeyCredential keyCredential1 = new KeyCredential();
byte[] customKeyIdentifier = Base64.getDecoder().decode("52ED9B5038A47B9E2E2190715CC238359D4F8F73");
keyCredential1.setCustomKeyIdentifier(customKeyIdentifier);
keyCredential1.setType("AsymmetricX509Cert");
keyCredential1.setUsage("Verify");
byte[] key1 = Base64.getDecoder().decode("base64MIIDADCCAeigAwIBAgIQfoIvchhpToxKEPI4iMrU1TANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMzAeFw0yMzAxMTIwODI3NTJaFw0yNDAxMTIwODQ3NTJaMBMxETAPBgNVBAMMCDIwMjMwMTEzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+iqg1nMjYmFcFJh/.../S5X6qoEOyJBgtfpSBANWAdA==");
keyCredential1.setKey(key1);
keyCredential1.setDisplayName("CN=20230113");
keyCredentials.add(keyCredential1);
application.setKeyCredentials(keyCredentials);
Application result = graphClient.applications().byApplicationId("{application-id}").patch(application);
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
const options = {
authProvider,
};
const client = Client.init(options);
const application = {
keyCredentials: [
{
endDateTime: '2024-01-11T15:31:26Z',
startDateTime: '2023-01-12T09:31:26Z',
type: 'AsymmetricX509Cert',
usage: 'Verify',
key: 'base64MIIDADCCAeigAwIBAgIQejfrj3S974xI//npv7hFHTANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExNDAeFw0yMzAxMTIwOTA4NThaFw0yNDAxMTIwOTI4NThaMBMxETAPBgNVBAMMCDIwMjMwMTE0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt5vEj6j1l5wOVHR4eDGe77HWslaIVJ1NqxrXPm/...+R+U7sboj+kUvmFzXI+Ge73Liu8egL2NzOHHpO43calWgq36a9YW1yhBQR1ioEchu6jmudW3rF6ktmVqQ==',
displayName: 'CN=20230114'
},
{
customKeyIdentifier: '52ED9B5038A47B9E2E2190715CC238359D4F8F73',
type: 'AsymmetricX509Cert',
usage: 'Verify',
key: 'base64MIIDADCCAeigAwIBAgIQfoIvchhpToxKEPI4iMrU1TANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMzAeFw0yMzAxMTIwODI3NTJaFw0yNDAxMTIwODQ3NTJaMBMxETAPBgNVBAMMCDIwMjMwMTEzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+iqg1nMjYmFcFJh/.../S5X6qoEOyJBgtfpSBANWAdA==',
displayName: 'CN=20230113'
}
]
};
await client.api('/applications/bb77f42f-dacb-4ece-b3e6-285e63c24d52')
.update(application);
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
<?php
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Generated\Models\Application;
use Microsoft\Graph\Generated\Models\KeyCredential;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new Application();
$keyCredentialsKeyCredential1 = new KeyCredential();
$keyCredentialsKeyCredential1->setEndDateTime(new \DateTime('2024-01-11T15:31:26Z'));
$keyCredentialsKeyCredential1->setStartDateTime(new \DateTime('2023-01-12T09:31:26Z'));
$keyCredentialsKeyCredential1->setType('AsymmetricX509Cert');
$keyCredentialsKeyCredential1->setUsage('Verify');
$keyCredentialsKeyCredential1->setKey(\GuzzleHttp\Psr7\Utils::streamFor(base64_decode('base64MIIDADCCAeigAwIBAgIQejfrj3S974xI//npv7hFHTANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExNDAeFw0yMzAxMTIwOTA4NThaFw0yNDAxMTIwOTI4NThaMBMxETAPBgNVBAMMCDIwMjMwMTE0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt5vEj6j1l5wOVHR4eDGe77HWslaIVJ1NqxrXPm/...+R+U7sboj+kUvmFzXI+Ge73Liu8egL2NzOHHpO43calWgq36a9YW1yhBQR1ioEchu6jmudW3rF6ktmVqQ==')));
$keyCredentialsKeyCredential1->setDisplayName('CN=20230114');
$keyCredentialsArray []= $keyCredentialsKeyCredential1;
$keyCredentialsKeyCredential2 = new KeyCredential();
$keyCredentialsKeyCredential2->setCustomKeyIdentifier(\GuzzleHttp\Psr7\Utils::streamFor(base64_decode('52ED9B5038A47B9E2E2190715CC238359D4F8F73')));
$keyCredentialsKeyCredential2->setType('AsymmetricX509Cert');
$keyCredentialsKeyCredential2->setUsage('Verify');
$keyCredentialsKeyCredential2->setKey(\GuzzleHttp\Psr7\Utils::streamFor(base64_decode('base64MIIDADCCAeigAwIBAgIQfoIvchhpToxKEPI4iMrU1TANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMzAeFw0yMzAxMTIwODI3NTJaFw0yNDAxMTIwODQ3NTJaMBMxETAPBgNVBAMMCDIwMjMwMTEzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+iqg1nMjYmFcFJh/.../S5X6qoEOyJBgtfpSBANWAdA==')));
$keyCredentialsKeyCredential2->setDisplayName('CN=20230113');
$keyCredentialsArray []= $keyCredentialsKeyCredential2;
$requestBody->setKeyCredentials($keyCredentialsArray);
$result = $graphServiceClient->applications()->byApplicationId('application-id')->patch($requestBody)->wait();
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
Import-Module Microsoft.Graph.Applications
$params = @{
keyCredentials = @(
@{
endDateTime = [System.DateTime]::Parse("2024-01-11T15:31:26Z")
startDateTime = [System.DateTime]::Parse("2023-01-12T09:31:26Z")
type = "AsymmetricX509Cert"
usage = "Verify"
key = [System.Text.Encoding]::ASCII.GetBytes("base64MIIDADCCAeigAwIBAgIQejfrj3S974xI//npv7hFHTANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExNDAeFw0yMzAxMTIwOTA4NThaFw0yNDAxMTIwOTI4NThaMBMxETAPBgNVBAMMCDIwMjMwMTE0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt5vEj6j1l5wOVHR4eDGe77HWslaIVJ1NqxrXPm/...+R+U7sboj+kUvmFzXI+Ge73Liu8egL2NzOHHpO43calWgq36a9YW1yhBQR1ioEchu6jmudW3rF6ktmVqQ==")
displayName = "CN=20230114"
}
@{
customKeyIdentifier = [System.Text.Encoding]::ASCII.GetBytes("52ED9B5038A47B9E2E2190715CC238359D4F8F73")
type = "AsymmetricX509Cert"
usage = "Verify"
key = [System.Text.Encoding]::ASCII.GetBytes("base64MIIDADCCAeigAwIBAgIQfoIvchhpToxKEPI4iMrU1TANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMzAeFw0yMzAxMTIwODI3NTJaFw0yNDAxMTIwODQ3NTJaMBMxETAPBgNVBAMMCDIwMjMwMTEzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+iqg1nMjYmFcFJh/.../S5X6qoEOyJBgtfpSBANWAdA==")
displayName = "CN=20230113"
}
)
}
Update-MgApplication -ApplicationId $applicationId -BodyParameter $params
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.models.application import Application
from msgraph.generated.models.key_credential import KeyCredential
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = Application(
key_credentials = [
KeyCredential(
end_date_time = "2024-01-11T15:31:26Z",
start_date_time = "2023-01-12T09:31:26Z",
type = "AsymmetricX509Cert",
usage = "Verify",
key = base64.urlsafe_b64decode("base64MIIDADCCAeigAwIBAgIQejfrj3S974xI//npv7hFHTANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExNDAeFw0yMzAxMTIwOTA4NThaFw0yNDAxMTIwOTI4NThaMBMxETAPBgNVBAMMCDIwMjMwMTE0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt5vEj6j1l5wOVHR4eDGe77HWslaIVJ1NqxrXPm/...+R+U7sboj+kUvmFzXI+Ge73Liu8egL2NzOHHpO43calWgq36a9YW1yhBQR1ioEchu6jmudW3rF6ktmVqQ=="),
display_name = "CN=20230114",
),
KeyCredential(
custom_key_identifier = base64.urlsafe_b64decode("52ED9B5038A47B9E2E2190715CC238359D4F8F73"),
type = "AsymmetricX509Cert",
usage = "Verify",
key = base64.urlsafe_b64decode("base64MIIDADCCAeigAwIBAgIQfoIvchhpToxKEPI4iMrU1TANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDDAgyMDIzMDExMzAeFw0yMzAxMTIwODI3NTJaFw0yNDAxMTIwODQ3NTJaMBMxETAPBgNVBAMMCDIwMjMwMTEzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+iqg1nMjYmFcFJh/.../S5X6qoEOyJBgtfpSBANWAdA=="),
display_name = "CN=20230113",
),
],
)
result = await graph_client.applications.by_application_id('application-id').patch(request_body)
Lea la documentación del SDK para obtener más información sobre cómo agregar el SDK al proyecto y crear una instancia de authProvider .
Respuesta
HTTP/1.1 204 No Content
Paso 3: Prueba de la autenticación solo de la aplicación
Puede probar la autenticación de solo aplicación con Microsoft Graph PowerShell, como se muestra en el ejemplo siguiente.
Solicitud
## Authenticate using the certificate thumbprint
Connect-MgGraph -ClientID cf34b10f-50fd-4167-acf6-4f08ddd4561b -TenantId 38d49456-54d4-455d-a8d6-c383c71e0a6d -CertificateThumbprint 52ED9B5038A47B9E2E2190715CC238359D4F8F73
## Authenticate using the certificate subject name
Connect-MgGraph -ClientID 588028ea-22c2-490e-8c6b-80cd06985e8c -TenantId 38d49456-54d4-455d-a8d6-c383c71e0a6d -CertificateName CN=20230113
Respuesta
Welcome To Microsoft Graph!
Para confirmar que está ejecutando la sesión de PowerShell de Microsoft Graph sin que un usuario haya iniciado sesión, ejecute la siguiente solicitud.
Get-MgContext
La respuesta es similar a la siguiente.
ClientId : cf34b10f-50fd-4167-acf6-4f08ddd4561b
TenantId : 38d49456-54d4-455d-a8d6-c383c71e0a6d
CertificateThumbprint :
Scopes :
AuthType : AppOnly
AuthProviderType : ClientCredentialProvider
CertificateName : CN=20230113
Account :
AppName : testApp
ContextScope : Process
Certificate :
PSHostVersion : 5.1.22621.963
ClientTimeout : 00:05:00
Conclusión
Ha usado Microsoft Graph para actualizar las credenciales de certificado de un objeto de aplicación. Este proceso es una alternativa mediante programación al uso de la Centro de administración Microsoft Entra. También puede actualizar las credenciales de certificado de una entidad de servicio siguiendo un proceso similar y llamando al punto de https://graph.microsoft.com/v1.0/servicePrincipals/ conexión.