Microsoft Graph API:访问令牌验证失败。无效观众

nim*_*rod 1 oauth-2.0 jwt azure-active-directory microsoft-graph-api

我正在尝试将我的应用程序从 Office 365 REST v2.0 迁移到 Microsoft Graph (v1.0)。令牌交换似乎正常工作,但当我尝试调用 API 时,我收到以下错误:

    (
    [errorNumber] => 401
    [error] => Request returned HTTP error 401
    [message] => {
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure. Invalid audience.",
    "innerError": {
      "date": "2021-03-16T15:36:21",
      "request-id": "dda1e33a-2774-4986-8c45-1487404fbb72",
      "client-request-id": "e842d9a8-d71b-0563-f1ce-e58052e5bdb9"
    }
  }
}
)
Run Code Online (Sandbox Code Playgroud)

access_token 具有以下受众:

"aud": "https://outlook.office.com"
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的端点:

https://login.microsoftonline.com/common/oauth2/v2.0/token
Run Code Online (Sandbox Code Playgroud)

有效负载:

grant_type=authorization_code
&code=0.AR8A3XwQy0FAmkSxxxx
&redirect_uri=https%3A%2F%2Fxxx.com%2Fproxy%2Foffice365authorize
&client_id=e2147faf-87f0-4e7f-xxxx-xxxxxxxxxxx
&client_secret=xxxxxxxxxxxx
Run Code Online (Sandbox Code Playgroud)

任何提示将不胜感激,谢谢!

Joy*_*ang 6

这意味着您的令牌有错误的受众,要调用 Microsoft Graph API,您需要获取 Microsoft Graph 的令牌,即访问令牌需要"aud": "https://graph.microsoft.com".

看起来您正在使用AAD 身份验证代码流来获取令牌,因此当您请求授权代码时,请使用带有https://graph.microsoft.com/.default.

https://login.microsoftonline.com/common/oauth2/authorize?
client_id=xxxxx
&response_type=code
&redirect_uri=xxxxxx
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345
Run Code Online (Sandbox Code Playgroud)

scope=https://graph.microsoft.com/.default请求令牌时也可使用。

POST https://login.microsoftonline.com/common/oauth2/v2.0/token

client_id=xxxxxx
&scope=https://graph.microsoft.com/.default
&code=0.AR8A3XwQy0FAmkSxxxx
&redirect_uri=xxxxxx
&grant_type=authorization_code
&client_secret=xxxxx
Run Code Online (Sandbox Code Playgroud)

要成功调用 API,还要确保您已为您的客户端应用程序授予正确的委派 Microsoft Graph API 权限,具体取决于您要调用的 API,例如,如果您要调用List users,则需要此处的权限。

在此输入图像描述