Upload local self-signed certificate to Entra Id application Python

264 views Asked by At

With Create a self-signed public certificate to authenticate your application | Microsoft Learn created certificate.

$certname = "{certificateName}"    ## Replace {certificateName}
$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256

Export-Certificate -Cert $cert -FilePath "C:\Users\admin\Desktop\$certname.cer"   ## Specify your preferred location

Any way to add this certificate to Entra Id app registration programatically using Python SDK?

enter image description here

1

There are 1 answers

0
Imran On

To upload certificate to the Azure AD application, you can try the below:

Generate the thumbprint and read the certificate key:

Get-PfxCertificate -Filepath "C:\Users\imran\Downloads\exchagecer.cer" | Out-File -FilePath "C:\Users\imran\Downloads\exchagecer.cer.thumbprint.txt"

[convert]::ToBase64String((Get-Content C:\Users\imran\Downloads\exchagecer.cer -Encoding byte))  | Out-File -FilePath "C:\Users\imran\Downloads\exchagecer.key.txt"

enter image description here

enter image description here

And use the below Microsoft Graph API query:

https://graph.microsoft.com/v1.0/applications/ObjectID

{
"keyCredentials": [
{
"endDateTime": "2024-01-11T15:31:26Z",
"startDateTime": "2023-11-20T15:31:26Z",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"key": AboveKey",
"displayName": "CN=20230112"
}
]
}

enter image description here

The certificate uploaded successfully like below:

enter image description here

To do the same in Python, make use of below code:

graph_client = GraphServiceClient(credentials, scopes)

request_body = Application(
    key_credentials = [
        KeyCredential(
            end_date_time = "2024-01-11T15:31:26Z",
            start_date_time = "2023-11-20T15:31:26Z",
            type = "AsymmetricX509Cert",
            usage = "Verify",
            key = base64.urlsafe_b64decode("CertificateKey"),
            display_name = "CN=20230112",
        ),
    ],
)

result = await graph_client.applications.by_application_id('application-id').patch(request_body)

Reference:

Add a certificate to an app or service principal using Microsoft Graph - Microsoft Graph | Microsoft