Log-In to AzureRM PowerShell module using oAuth Tokens

1 minute read

In my last post, I demonstrated how to generate Azure AD oAuth tokens using my AzureServicePrincipalAccount PowerShell module.

Although personally, I pretty much use Azure Resource Manager REST API for everything – this is where the oAuth token come in play, but often, I have seen colleagues and customers use a mixture of both ARM REST APIs calls and AzureRM modules within same PowerShell scripts. This could potentially be troublesome because in order to use AzureRM modules, you will need to sign-in to Azure using Add-AzureRMAccount (or it’s alias Login-AzureRMAccount). Luckily, Add-AzureRMAccount also supports signing in using an existing AAD oAuth token. So, if you have already generated an oAuth token for invoking ARM REST APIs, you can continue using this token for AzureRM modules. here’s how you do it:

#variables
$TenantId = '1239054d-9f01-46eb-b7a4-b301e424c6fe'
$SubscriptionId = '412510db-cea0-40c4-95e3-f9818e279ef7'
$AccountId = 'you@yourcompany.onmicrosoft.com'

#Login to Azure
Write-Output 'Login to Azure'
#generate oAuth token and construct request header for ARM API calls
$token = Get-AzureADToken -TenantId $TenantId -UserName $AccountId
$ARMRequestHeaders = @{'Authorization' = $token}

#use existing token to sign-in to AzureRM modules
Add-AzureRmAccount -TenantId $TenantId -Subscription $SubscriptionId -AccessToken $token.substring(7, ($token.length -7)) -AccountId $AccountId

Note: Since the token generated by Get-AzureADToken from my AzureServicePrincipalAccount module has the “bearer” prefix already added, when using it in Add-AzureRMAccount, you will need to remove this prefix, as you can see from this code sample, I’m removing the first 7 characters of the oAuth token returned from Get-AzureADToken command.

Leave a comment