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.

profile.ps1
 
 
 
 
 
4.8 Star
(8)
5,407 times
Add to favorites
Windows Azure
10/24/2019
E-mail Twitter del.icio.us Digg Facebook
Sign in to ask a question


  • multiple_matching_tokens_detected
    3 Posts | Last post Wed 3:15 AM
    • 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