Upload Certificate to App Registration Using PowerShell

This Graph API PowerShell article will show how to create a self-signed certificate on a Windows machine and upload it to an App Registration using Graph API.

The Graph API PowerShell wrapper gives us programmatically access to all Microsoft 365 and Azure services using REST API access and PowerShell.

The advantage of PowerShell with Graph API is that it handles the API requests and reduces the amount of code needed to contract API calls to the Service.

Create a Self Signed Certificate

The first step we need to take is creating a self-signed certificate on a Windows machine. To do it, Open a PowerShell console and run the following code.

Make sure you note down the certificate name (in our case, the cert CN name is GraphApi

$cert = New-SelfSignedCertificate -Subject "CN=GraphApi" -CertStoreLocation `
  "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 `
  -KeyAlgorithm RSA -HashAlgorithm SHA256
Export-Certificate -Cert $cert -FilePath "./GraphApi.cer"

Convert Certificate

Next, we must convert the newly created certificate’s thumbprint using the following code.

Note: Make sure you change the file paths in the cmdlet

Get-PfxCertificate -Filepath “GraphApi.cer” | Out-File -FilePath “thumbprint.txt”

[convert]::ToBase64String((Get-Content “GraphApi.cer” -AsByteStream -Raw ))  | Out-File -FilePath “key.txt”

Upload Certificate

The final step will be to upload the certificate to an Azure App Registration. Before you run the code, add the cert key from the key.txt file and log in to Azure.

Import-Module Microsoft.Graph.Applications

$params = @{
	keyCredentials = @(
			type = "AsymmetricX509Cert"
			usage = "Verify"
			key = [System.Text.Encoding]::ASCII.GetBytes("CERT KEY from Key.txt
			displayName = "CN=GraphApi"

Update-MgApplication -ApplicationId 'App Object ID' -BodyParameter $params -verbose 






Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.