The enterprise always loves to increase the security posture. One authentication approach enterprise takes in Azure is App registration with a service principal. The advantage here is that the service principal can use certificates to authenticate instead of passwords. Certificates are secure than passwords as those can be centrally managed.
Problem
Solution
################ Azure login params ################### | |
$ServicePrincipalCertificateThumbprint = '' | |
$TenantId = '' #This is AAD Tenant Id where the below app registration is created, not Subscription Id | |
$ApplicationId = '' #THis is the application registration id sometimes called clientId. Make sure this app registration has permission to send message. | |
################# One time install #################### | |
$azAccountsInstalled = Get-InstalledModule Az.Accounts | |
if( ! $azAccountsInstalled) { | |
Install-Module Az.Accounts -AllowClobber | |
} | |
else{ | |
Write-Host "Az.Accounts already present" -ForegroundColor Yellow | |
} | |
####################################################### | |
# Connect using service principal and validations | |
# If running from Linux use certificate path https://docs.microsoft.com/en-us/powershell/module/az.accounts/connect-azaccount?view=azps-6.4.0#example-9--connect-using-certificate-file | |
Connect-AzAccount -CertificateThumbprint $ServicePrincipalCertificateThumbprint -SendCertificateChain -ApplicationId $ApplicationId -Tenant $TenantId -ServicePrincipal |
# Change the -ResourceUrl based on scenario. Below is for ServiceBus | |
$accessToken = Get-AzAccessToken -ResourceUrl https://servicebus.azure.net/ |
Please note that the Az.Accounts need a minimum of Windows PowerShell 5.1 or PowerShell 7 version.
Limitations
It reads the certificate from the personal store unless loaded from a file. We cannot pass an X509Certificate object to the Connect-AzAccount cmdlet. There is already an issue in GitHub to track it.
Update : 2021-10-30
What if we don't have permission to install Az.Accounts module?
Recently, I came to one production debugging situation where there is no permission to install the Az.Accounts module and even no connectivity to the internet to get the module. The only way is to write everything ourselves. Fortunately, someone had already done that and it is available publicly. If interested read the official docs.
2 comments:
Yeah. It is in open state for the last 2 years.
Hi Team, Your explanation about "Azure Enterprise - PowerShell log in as service principal + certificate and generate JWT access token" I was pleased to see. Your description of the troubleshooting scenario, as close to how the application works, and the coding you provided are helpful. It was easy to understand for me. Thanks for Sharing your Info!!!
Post a Comment