Client Secrets und Zertifikate von Azure Apps ersetzen

Um über Azure Apps einen Authentifizierungstoken zu beziehen ist entweder ein Client Secret Key oder Zertifikat erforderlich. Beide Methoden anzulegen ist nicht viel Aufwand und gibt einem die Option sich über verschiedene Arten an den Microsoft APIs zu authentifizieren.

In einer Azure App sind jeweils die Optionen Zertifikat und Client Secret verfügbar. Mit Zertifikat oder Client Secret liefert der Tenant einen Authentifizierungstoken für den Zugriff auf APIs wie Microsoft Graph.

Sowohl Zertifikat als auch Client Secret können im Browser hochgeladen/gesetzt werden. Mit PowerShell gibt es weitere Optionen, beispielsweise lässt sich definieren wie lange Zertifikate oder Client Secrets gültig sein sollen. In dem Beitrag findest du Anleitungen um via PowerShell neue Client Secrets bzw. alternativ ein neues Zertifikat anzulegen, oder bestehende Zertifikate einzusetzen.


Erstellen von neuen Client Secrets

Anforderungen:

  1. Verbindung zum Azure Tenant und laden der bisherigen Azure App Credentials. Sind noch keine erstellt worden wird es keine zurückgeben.
PowerShell
$AppID = "[ApplicationID]"

Import-Module Az
Connect-AzAccount
$AzureAppPasswordCred = Get-AzADAppCredential -ApplicationId $AppID | where Type -eq Password
$AzureAppPasswordCred 
$CurrentSecretKey = $AzureAppPasswordCred[0]
  1. Type Password zeigt an es handelt sich bei den Credentials um einen Client Secret. In meinem Beispiel läuft der Secret Key im Februar 2022 ab. Ich möchte es vorab um 5 Jahre verlängern und den alten Key ersetzen.
  2. Da New-AzADAppCredential ein vordefiniertes Passwort möchte lasse ich mir eines generieren und konvertiere es in einen SecureString. Alternativ kann jemand selbst ein Passwort definieren. Am Ende muss es ein SecureString sein.
PowerShell
$Bytes = New-Object Byte[] 32
$RandBytes = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$RandBytes.GetBytes($Bytes)
$RandBytes.Dispose()

$NewClientSecret = [System.Convert]::ToBase64String($Bytes)
$NewClientSecretSecureString = ConvertTo-SecureString -String $NewClientSecret -AsPlainText -Force
  1. Mit dem neu generierten Client Secret kann ich über New-AzADAppCredential der Azure App den neuen Client Secret setzen und die Laufzeit individuell definieren. Abschliessend soll es den neuen Client Secret Key im Klartext ausgeben.
PowerShell
$StartDateTime = [System.DateTime]::Now
$EndDateTime = $StartDateTime.AddMonths(60)
New-AzADAppCredential -ApplicationId $AppID -Password $NewClientSecretSecureString -StartDate $StartDateTime -EndDate $EndDateTime
$NewClientSecret
  1. Eine Kontrolle im Browser wird nun beide Client Secret Keys in der Liste mit Ablaufdatum 2022 und 2026 zeigen.
  1. Dadurch kann ich den alten Key von Februar 2022 löschen und die Anmeldemöglichkeit für den Key entziehen.
PowerShell
Remove-AzADAppCredential -ApplicationId $AppID -KeyId $CurrentSecretKey.KeyId
PowerShell
# Generate a new client secret key for an Azure App and remove the previous one.
# For my post at https://blog.topedia.com/?p=6453#ClientSecret
#
# Requirements
#   - Az PowerShell Module 
#   - An existing Azure App Registration

# Defining the Azure App ID
$AppID = "[ApplicationID]"

# Connecting the Azure tenant and loading the current Azure App credentials
Import-Module Az
Connect-AzAccount
$AzureAppPasswordCred = Get-AzADAppCredential -ApplicationId $AppID | where Type -eq Password
$AzureAppPasswordCred 
$CurrentSecretKey = $AzureAppPasswordCred[0]

# Generating a new random password for the client secret
$Bytes = New-Object Byte[] 32
$RandBytes = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$RandBytes.GetBytes($Bytes)
$RandBytes.Dispose()
$NewClientSecret = [System.Convert]::ToBase64String($Bytes)
$NewClientSecretSecureString = ConvertTo-SecureString -String $NewClientSecret -AsPlainText -Force

# Defining how long the new key should be valid, in months
$StartDateTime = [System.DateTime]::Now
$EndDateTime = $StartDateTime.AddMonths(60)

# Adding the new client secret to the Azure app
New-AzADAppCredential -ApplicationId $AppID -Password $NewClientSecretSecureString -StartDate $StartDateTime -EndDate $EndDateTime
$NewClientSecret 

# Removing the previous key
if($CurrentSecretKey.Count -eq 1)
{ Remove-AzADAppCredential -ApplicationId $AppID -KeyId $CurrentSecretKey.KeyId }

Erstellen von neuem Zertifikat

Anforderungen:

Neben Client Secret gibt es die Möglichkeit sich über ein Zertifikat anzumelden. Im Beispiel erstelle ich ein selbstsigniertes Zertifikat das für den Einsatz mit einer Azure App ausreichend ist. Ist bereits ein signiertes Zertifikat vorhanden kann es ebenfalls eingesetzt werden, siehe nächster Abschnitt.

  1. Erstelle über New-SelfSignedCertificate ein neues, selbstsigniertes Zertifikat, definiere den Namen und wie lange es gültig sein soll.
PowerShell
$NewCert = New-SelfSignedCertificate -Subject "CN=TAMSharePointAzureApp" -KeyAlgorithm RSA -HashAlgorithm sha256 -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -NotAfter (get-date).AddYears(5) -KeyUsage DigitalSignature

1b: Optional für den Export des öffentlichen Schlüssels vom neuen Zertifikat, falls man es beispielweise manuell zur App Registration hochladen möchte. Wird es mit den nachfolgenden Schritten via PowerShell übertragen kann dieser Punkt übersprungen werden.

PowerShell
Export-Certificate -Cert $NewCert -FilePath "[ExportPath]\Certificate.cer" -Force
  1. Stelle eine Verbindung zum Azure Tenant her.
PowerShell
Import-Module Az
Connect-AzAccount
  1. Mit dem erstellten Zertifikat speichert es am Rechner den privaten und öffentlichen Schlüssel. Die Azure App möchte den öffentlichen Schlüssel. Über die Daten des Zertifikats kann es mit PowerShell an die App angefügt werden. Beachte die AppID anzupassen.
PowerShell
$AppID = "[ApplicationID]"

$CertValue = $NewCert.GetRawCertData()
$CertValue = [System.Convert]::ToBase64String($CertValue)

New-AzADAppCredential -ApplicationId $AppID -CertValue $CertValue -StartDate $NewCert.NotBefore -EndDate $NewCert.NotAfter
  1. Im Browser wird es jetzt in der App das hochgeladene Zertifikat mit Thumbprint und Laufzeit anzeigen.
  1. Wurden beide Schritte für Client Secret und Zertifikat ausgeführt wird PowerShell nun zwei Credentials aufführen. Mit der App ist in dem Zustand eine Anmeldung via Client Secret und Zertifikat möglich.
  • Type AsymmetricX509Cert ist die Authentifizierung über Zertifikat.
  • Type Password ist die Authentifizierung über Client Secret.
PowerShell
# Generate a new certificate for an Azure App authentication
# For my post at https://blog.topedia.com/?p=6453#NewCertificate
#
# Requirements
#   - Az PowerShell Module 
#   - An existing Azure App Registration

# Define the Azure AppID
$AppID = "[ApplicationID]"

# Creating a new self-signed certificate for 5 years
$NewCert = New-SelfSignedCertificate -Subject "CN=TAMSharePointAzureApp" -KeyAlgorithm RSA -HashAlgorithm sha256  -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -NotAfter (get-date).AddYears(5) -KeyUsage DigitalSignature

# Connecting the Azure tenant
Import-Module Az
Connect-AzAccount

# Adding the new certificate to the Azure app
$CertValue = $NewCert.GetRawCertData()
$CertValue = [System.Convert]::ToBase64String($CertValue)
New-AzADAppCredential -ApplicationId $AppID -CertValue $CertValue -StartDate $NewCert.NotBefore -EndDate $NewCert.NotAfter

# Receiving updated Azure App credentials
Get-AzADAppCredential -ApplicationId $AppID

Bestehende Zertifikate einsetzen

Anforderungen:

Ein bestehendes Zertifikat einzusetzen ist ähnlich wie die Erstellung von einem neuem Zertifikat. Der Teil über die Neuerstellung wird ersetzt mit dem Laden des bestehenden Zertifikats. Die Azure App möchte den öffentlichen Schlüssel des Zertifikats. Dadurch muss der öffentliche Schlüssel entweder bereits exportiert sein, oder das Zertifikat ist am lokalen Rechner mit privatem Schlüssel vorhanden.

1a. Ist das Zertifikat mit privatem Schlüssel am Rechner vorhanden,…

PowerShell
$CertThumbprint = "[CertificateThumbprint]"
$Cert = (Get-ChildItem -Path cert:\* -Recurse | where Thumbprint -eq $CertThumbprint)[0]

1b. oder wurde der öffentliche Schlüssel bereits exportiert ist der Speicherpfad erforderlich.

PowerShell
$Cert = "[CertExportPath]"
  1. Laden des öffentlichen Schlüssels.
PowerShell
$CertObj = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2($Cert)
$CertValue = $CertObj.GetRawCertData()
$CertValue = [System.Convert]::ToBase64String($CertValue)
  1. Danach ist es identisch zum Vorgang mit neuem Zertifikat. Stelle eine Verbindung zum Azure Tenant her.
PowerShell
Import-Module Az
Connect-AzAccount
  1. Man fügt der Azure App ein Zertifikat hinzu und könnte sich damit authentifizieren. Beachte die AppID anzupassen.
PowerShell
$AppID = "[ApplicationID]"

New-AzADAppCredential -ApplicationId $AppID -CertValue $CertValue -StartDate $CertObj.NotBefore -EndDate $CertObj.NotAfter
  1. Wurde mit dem Zertifikat ein bestehendes ergänzt zeigt die Kontrolle aller Credentials nun 3 Einträge. Zwei Zertifikate und einen Client Secret.
  1. Ähnlich wie mit Client Secret lässt sich ein nicht mehr benötigtes Zertifikat löschen.
PowerShell
Remove-AzADAppCredential -ApplicationId $AppID -KeyId [KeyId]
PowerShell
# Use an existing certificate for an Azure App authentication.
# For my post at https://blog.topedia.com/?p=6453#ExistingCertificate
#
# Requirements
#   - Az PowerShell Module 
#   - An existing Azure App Registration

# Define the Azure AppID
$AppID = "[ApplicationID]"

# In case the certificate is stored on the local machine...
$CertThumbprint = "[CertificateThumbprint]"
$Cert = (Get-ChildItem -Path cert:\* -Recurse | where Thumbprint -eq $CertThumbprint)[0]

# OR if the public key has already been exported the filepath to the exported certificate
$Cert = "[CertExportPath]"

# Loading the public key
$CertObj = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2($Cert)
$CertValue = $CertObj.GetRawCertData()
$CertValue = [System.Convert]::ToBase64String($CertValue)

# Connecting the Azure tenant
Import-Module Az
Connect-AzAccount

# Adding the certificate to the Azure app
New-AzADAppCredential -ApplicationId $AppID -CertValue $CertValue -StartDate $CertObj.NotBefore -EndDate $CertObj.NotAfter

# Removing an old certificate
Remove-AzADAppCredential -ApplicationId $AppID -KeyId [KeyId]
Share this post:

About the Author

Tobias Asböck

Tobias Asböck

Tobias is a Senior System Engineer with more than 10 years of professional experience with Microsoft 365 products such as SharePoint Online, OneDrive for Business, Teams Collaboration, Entra ID, Information Protection, Universal Print, and Microsoft 365 Licensing. He also has 15+ years of experience planning, administering, and operating SharePoint Server environments. In his spare time, Tobias is busy with updates in the Microsoft 365 world or on the road with his road bike and other sports activities. If you have additional questions, please contact me via LinkedIn or support@topedia.com.

No comments yet