PowerShell

How to generate bearer token value for Azure REST API headers without AzureRm.Profile?

I was doing Azure REST API demo at my work place where a good ask popped up “Why Get-AzureRMContext cmdlet to generate bearer token?” We need to fall back with ARM module to work with REST based codes, right?

Yes, if we look at this solution – ARM module is prerequisite! And REST API can be called using the token generated by this function.

function Get-AzureRmCachedAccessToken()
{
    $ErrorActionPreference = 'Stop'
    if (-not (Get-Module AzureRm.Profile)) 
    {
        Import-Module AzureRm.Profile
    }
    $azureRmProfileModuleVersion = (Get-Module AzureRm.Profile).Version
    if ($azureRmProfileModuleVersion.Major -ge 3) 
    {
        $azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
        if (-not $azureRmProfile.Accounts.Count) 
        {
            Write-Error "Ensure you have logged in before calling this function."    
        }
    }
    else 
    {
        $azureRmProfile = [Microsoft.WindowsAzure.Commands.Common.AzureRmProfileProvider]::Instance.Profile
        if (-not $azureRmProfile.Context.Account.Count) 
        {
            Write-Error "Ensure you have logged in before calling this function."    
        }
    }
    $currentAzureContext = Get-AzureRmContext
    $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile)
    Write-Debug ("Getting access token for tenant" + $currentAzureContext.Subscription.TenantId)
    $token = $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId)
    $token.AccessToken
}

Gist for reference!

So, here comes the PowerShell way to generate the bearer token.

function Get-AzureRMBearerToken
{
    [CmdletBinding()]
    Param
    (
        $TenantID,

        $AppID,

        $ClientSecret
    )

    $Result=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TenantID/oauth2/token?api-version=1.0 -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "$APPID"; "client_secret" = "$PASSWORD" }
    $Authorization = "{0} {1}" -f ($result.token_type , $result.access_token)
    $Authorization
}
Get-AzureRMBearerToken  -TenantID "<61cf51c2-e535-4435-b337-21f497e1ca0b>" -AppID "<62196c4e-4dd1-4d17-b311-3eb3824d7cc0>" -ClientSecret "<YOUR SUPER SECRET CLIENT KEY>"

Plan for your credentials and security!

Leave a Reply

Your e-mail address will not be published. Required fields are marked *