Create and Azure Application & SPN with Certificate Authentication

This PowerShell code snippet creates an Azure AD application registration with an associated SPN and self-signed certificate for Azure authentication.

I've used this for generating certificates that Virtual Machines can use for authenticating to Azure as an alternative to Managed Identities.

  Script Purpose
     To create authentication capable certificates and SPN for Azure Access.
     Script must be run elevated
#Set the new App Registration name
$identifier = "azapp-diskencryption-ase"
#Create a Password for the generated Cert
$password   = “CertPaSSw0rd”
$SubscriptionName       = "Laurie Demo"
# 1.  Ensure Authenticated
Try {
} Catch {
  if ($_ -like "*Run Login-AzureRmAccount to login*") {
Select-AzureRmSubscription –SubscriptionName $SubscriptionName 
# 2. Establish certificate validity period
# Define certificate start and end dates
$currentDate = Get-Date 
$endDate  = $currentDate.AddYears(1)
$notAfter = $endDate.AddMinutes(1)
# Generate new self-signed certificate from elevated PowerShell session
$certName = "$($identifier)"
$certStore ="Cert:\LocalMachine\My"
$certThumbprint = (New-SelfSignedCertificate `
-DnsName "$certName" `
-CertStoreLocation $CertStore `
-KeyExportPolicy Exportable `
-Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" `
-NotAfter $notAfter).Thumbprint
# 3. Export password-protected pfx file
$pfxPassword = ConvertTo-SecureString $Password -AsPlainText -Force
$pfxFilepath = "$($env:TEMP)\temp\$($identifier).pfx"
Export-PfxCertificate `
-Cert "$($certStore)\$($certThumbprint)" `
-FilePath $pfxFilepath `
-Password $pfxPassword
# Create Key Credential Object
$cert = New-Object `
-TypeName System.Security.Cryptography.X509Certificates.X509Certificate `
-ArgumentList @($pfxFilepath, $pfxPassword)
$keyValue =
Import-Module -Name AzureRM.Resources 
Write-Output "Creating AAD application..."
$azureAdApplication = New-AzureRmADApplication -DisplayName $identifier  -IdentifierUris "$($identifier)" 
Write-Output "Creating AAD service principal..."
$servicePrincipal = New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId -CertValue $keyValue `
   -StartDate $currentDate -EndDate $endDate