You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Office 365 Graph API应用仅访问认证失败:无效受众问题求助

配置Microsoft Graph API应用仅访问权限时出现「Invalid audience」认证错误

我在配置Microsoft Graph API的应用仅访问(app only access)权限时遇到问题,认证时出现错误:Access token validation failure. Invalid audience.

我的代码如下:

import requests
tenant = 'widgetsinc'
token_request_url = 'https://login.microsoftonline.com/{}/oauth2/v2.0/token'.format(tenant)
auth_payload = {
                    'client_id': 'deaf-beef-cafe',
                    'scope': 'api://deaf-beef-cafe/.default',
                    'client_secret': 'hunter2',
                    'grant_type': 'client_credentials'
                }

x = requests.post(token_request_url, data=auth_payload)
token = x.json()
print(token)

url = "https://graph.microsoft.com/v1.0/users"
payload={'Authorization':token['access_token']}

x = requests.post(url, headers=payload)

print(x.json())
exit()

print(token)的输出结果:

{
'token_type': 'Bearer',
'expires_in': 3599,
'ext_expires_in': 3599,
'access_token': 'REMOVED'
}

print(x.json())的输出结果:

{
'error': {
'code': 'InvalidAuthenticationToken',
'message': 'Access token validation failure. Invalid audience.',
'innerError': {
'date': '2023-01-25T00:38:48',
'request-id': 'removed',
'client-request-id': 'this also removed'
}
}
}

我的应用已在网页端添加Microsoft Graph的应用权限(如User.Read.All等)。


问题原因

请求token时指定的scope为api://deaf-beef-cafe/.default,这个scope对应的是自定义API的受众,而你要访问的是Microsoft Graph API,导致生成的token受众(aud字段)不是https://graph.microsoft.com,因此验证失败。另外,调用用户列表接口用了POST请求,不符合Graph API的规范。

解决步骤

  1. 修正token请求的scope:将auth_payload中的scope值改为https://graph.microsoft.com/.default,这是获取Microsoft Graph应用仅访问权限的正确scope。
  2. 修正请求方法:调用https://graph.microsoft.com/v1.0/users接口需使用GET请求,而非POST。
  3. 补全Authorization头格式:Authorization头需要加上Bearer 前缀,否则认证会失败。

修改后的完整代码:

import requests
tenant = 'widgetsinc'
token_request_url = 'https://login.microsoftonline.com/{}/oauth2/v2.0/token'.format(tenant)
auth_payload = {
                    'client_id': 'deaf-beef-cafe',
                    'scope': 'https://graph.microsoft.com/.default',
                    'client_secret': 'hunter2',
                    'grant_type': 'client_credentials'
                }

x = requests.post(token_request_url, data=auth_payload)
token = x.json()
print(token)

url = "https://graph.microsoft.com/v1.0/users"
headers={'Authorization': f"Bearer {token['access_token']}"}

x = requests.get(url, headers=headers)

print(x.json())
exit()

额外验证点

  • 确认租户值widgetsinc是正确的租户域名或租户ID
  • 检查应用的client_secret是否有效、未过期
  • 确保已对添加的Microsoft Graph应用权限完成管理员同意,否则会出现权限不足的错误

内容的提问来源于stack exchange,提问作者Office Drone 7324

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:46:03