Skip to content

Instantly share code, notes, and snippets.

@JanVidarElven
Last active November 20, 2023 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JanVidarElven/963e81792caafc59b26591bef0f80f34 to your computer and use it in GitHub Desktop.
Save JanVidarElven/963e81792caafc59b26591bef0f80f34 to your computer and use it in GitHub Desktop.
Application Certificate Credentials
# Connecting with Azure AD PowerShell Module to Manage Application Credentials for Self Signed Certificates
# Connecting to Tenant
$tenantId = 'elven.onmicrosoft.com'
Connect-AzureAD -TenantId $tenantId
# Get an existing application and set some variables
$myApp = Get-AzureADApplication -SearchString "MyDemoCertApp"
$appId = $myApp.AppId
$appObjectId = $myApp.ObjectId
# Cert path and FQDN
$certPath = 'C:\_Certs\MyDemoAppSelfSignedCert.pfx'
$certFqdn = 'no.elven.mydemoappspn'
# Create the self signed cert
$currentDate = Get-Date
$endDate = $currentDate.AddYears(2)
$notAfter = $endDate.AddYears(2)
$pwd = "<TYPE PWD FOR PRIVATE KEY HERE>"
$thumb = (New-SelfSignedCertificate -CertStoreLocation cert:\currentuser\my -DnsName $certFqdn -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
$pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
Export-PfxCertificate -cert "cert:\currentuser\my\$thumb" -FilePath $certPath -Password $pwd
# Load the certificate
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate($certPath, $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
# Add the cert credential to your application
$myCustomKey = ($env:COMPUTERNAME) + "" + $currentDate.Day + $currentDate.Month
$myCustomKey = $myCustomKey.replace("-","")
New-AzureADApplicationKeyCredential -ObjectId $appObjectId -CustomKeyIdentifier $myCustomKey -StartDate $currentDate -EndDate $endDate -Type AsymmetricX509Cert -Usage Verify -Value $keyValue
Write-Host "Take note of this certificate thumbprint: $thumb"
# Optional: Try to connect with the cert credential
# Requirements: Install the MSAL.PS module from PSGallery
$thumb = '<THUMBPRINT HERE>'
$cert = Get-Item Cert:\CurrentUser\My\$thumb
$response = Get-MsalToken -TenantId $tenantId -ClientId $appId -ClientCertificate $cert -ForceRefresh
$response.accesstoken | clip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment