This post is sort of a follow up on a previous post where I attempted to prevent a duplicate login when accessing both Azure Resource Manager and Azure AD in the same PowerShell script, still without success by the way. But I can use something I learned there to accomplish something else: getting an access token for working with the Azure REST API.

Getting the access token

Getting the access token follows the same steps as described in my earlier post:

$rmAccount = Add-AzureRmAccount -SubscriptionId $subscriptionId
$tenantId = (Get-AzureRmSubscription -SubscriptionId $subscriptionId).TenantId
$tokenCache = $rmAccount.Context.TokenCache
$cachedTokens = $tokenCache.ReadItems() `
        | where { $_.TenantId -eq $tenantId } `
        | Sort-Object -Property ExpiresOn -Descending
$accessToken = cachedTokens[0].AccessToken

Of course, you have to login using an account that has sufficient permissions to access the REST API.

Using the token

We can now use the token to call the REST API. For example, to retrieve all the resource groups in a subscription. The easiest way is via the Invoke-RestMethod PowerShell cmdlet:

$apiVersion = "2017-05-10"
Invoke-RestMethod -Method Get `
                  -Uri ("https://management.azure.com/subscriptions/" + $subscriptionId +
                        "/resourcegroups" +
                        "?api-version=" + $apiVersion) `
                  -Headers @{ "Authorization" = "Bearer " + $accessToken }

The original article was posted on: ronaldwildenberg.com

Related articles

  • Application Modernization
  • Digital Workspace
  • Cloud Infrastructure
  • ITTS (IT Transformation Services)
  • Managed Security Operations
  • Multi-Cloud Platform
  • Backup & Disaster Recovery
Visit our knowledge hub
Visit our knowledge hub
ITQ

Let's talk!

Knowledge is key for our existence. This knowledge we use for disruptive innovation and changing organizations. Are you ready for change?

"*" indicates required fields

Your first name*
Your last name*