简体   繁体   中英

Access token validation failure for AD graph API after using the token acquired from AzureRmContext in Powershell

I am trying to make API calls to Microsoft graph API using Oauth2 to log in.

I tried to use AzureRm cmdlet to get the token for my account, so I can make the API calls, but the message "Access token validation failure. Invalid audience." showed up in the JSON response.

Login-AzureRmAccount

$currentAzureContext = Get-AzureRmContext
$tenantId = $currentAzureContext.Tenant.Id
$accountId = $currentAzureContext.Account.Id

$tokenCache = $currentAzureContext.TokenCache
$cachedTokens = $tokenCache.ReadItems() `
        | where { $_.TenantId -eq $tenantId }

$accessToken = $cachedTokens.AccessToken
Invoke-RestMethod -Method Get `
                 -Uri ("https://graph.microsoft.com/v1.0/me") `
                -Headers @{ "Authorization" = "Bearer " + $accessToken }

The following is the JSON response:

Invoke-RestMethod : {
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure. Invalid audience.",
    "innerError": {
      "request-id": "8429e520-401b-4382-adad-4f55bccbe752",
      "date": "2019-11-04T16:53:27"
    }
  }
}

Have a look at the token in https://jwt.ms and see what is the aud claim. I think the token you get via AzureRm is an access token to the Azure Management APIs. The value for MS Graph is ' https://graph.microsoft.com '. You can use the AzureAD PS module to get Graph tokens. Also note that AAD is notthe same as MS Graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM