Last active
November 20, 2023 13:04
-
-
Save JanVidarElven/963e81792caafc59b26591bef0f80f34 to your computer and use it in GitHub Desktop.
Application Certificate Credentials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment