Easily obtain AccessToken(Bearer) from an existing Az/AzureRM PowerShell session

You'll find in this function an easy way to extract the information required for you to build a Bearer token and all this from YOUR credentials within an authenticated PowerShell Azure session. You can then use this token to talk to Azure Resource Manager REST API.

4.8 Star
7,685 times
Add to favorites
Windows Azure
E-mail Twitter del.icio.us Digg Facebook
  • Exception when creating RMProfileClient under Core and Az.Accounts
    2 Posts | Last post March 06, 2020
    • I am using Az* modules in PowerShell Core/6+ and I get the error below when executing the following line from the script ...
      $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azProfile)
      Exception calling "AcquireAccessToken" with "1" argument(s): "Could not load type 'System.Security.Cryptography.SHA256Cng' from assembly 'System.Core, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'."
    • What version of Az PowerShell are you using? 
  • multiple_matching_tokens_detected
    3 Posts | Last post December 11, 2019
    • Thank you for this!  Though I have an issue:  The line
      $token = $profileClient.AcquireAccessToken($currentAzureContext.Tenant.TenantId)
      throws an error:
      Exception calling "AcquireAccessToken" with "1" argument(s): "multiple_matching_tokens_detected: The cache contains multiple tokens satisfying the requirements. Call AcquireToken again providing more arguments (e.g. UserId)"
      Is it possible to pass this additional argument to get the specified token?
      Or should I instead somehow be clearing the token cache before hand?
    • I got it.  So yes, I needed to clear the token cache before connecting to the Azure account.  But the only way I could find to do this was using an AzureRM command, rather than an Az module command (which is what I was using in Powershell).  But it turns out there's a way to use AzureRM commands by enabling those aliases.  So this is what I'm doing in the scripts now before connecting, which has fixed the error:
      Enable-AzureRmAlias -Scope CurrentUser
      Clear-AzureRmContext -Force
      I also just want to note that by returning the token as a string, when it is used in the Invoke-Method API call as part of the headers, it needs to be put into a dictionary (as headers parameter is supposed to be a dictionary).  So, something like this:
      $header = Get-AzBearerToken
      Invoke-RestMethod -Method PUT -Headers @{Authorization = $header }
    • Nevermind….you CAN use an Az module for clearing the cache:  Clear-AzContext -Force.
  • Very Cool
    2 Posts | Last post February 09, 2019
    • Very cool, and usefull was looking for something like this.
      also nice that it is prepared/works with the az cmdlets as well.
    • Very glad you find it useful