使用Python访问Microsoft Graph API遇<401>无效受众错误求助
解决方案:修复Microsoft Graph API 401 Invalid Audience错误
核心原因
Invalid Audience错误说明你获取的Bearer令牌的**受众(aud声明)**与Microsoft Graph API的预期受众不匹配。你的代码使用了旧版Azure AD OAuth2端点,导致令牌受众指向旧版Azure AD Graph(https://graph.windows.net),而非Microsoft Graph(https://graph.microsoft.com)。
具体修复步骤
替换为v2.0令牌端点
将请求令牌的URL从https://login.microsoftonline.com/{myTenant}/oauth2/token改为https://login.microsoftonline.com/{myTenant}/oauth2/v2.0/token,v2端点会根据scope参数正确生成面向Microsoft Graph的受众令牌。修正
scope参数格式scope在表单数据中必须是字符串格式,而非列表。你的代码中传了列表会导致请求参数解析异常,需要改为字符串"https://graph.microsoft.com/.default"。验证令牌受众
解码获取到的access_token,查看其中的aud字段,确认其值为https://graph.microsoft.com。如果不是,说明令牌生成过程存在问题,需重新检查端点和scope参数。
修正后的完整代码
import requests myBody = { 'client_id': '<clientID>', 'scope': 'https://graph.microsoft.com/.default', # 改为字符串格式 'client_secret': '<client secret>', 'grant_type': 'client_credentials' } # 使用v2.0令牌端点 token_response = requests.post('https://login.microsoftonline.com/{myTenant}/oauth2/v2.0/token', data=myBody) token_response.raise_for_status() # 添加错误捕获,便于排查请求失败问题 token_data = token_response.json() access_token = token_data['access_token'] myHeaders = { 'Authorization': f'Bearer {access_token}' # GET接口无需Content-Type: application/json,可移除该头 } users_response = requests.get('https://graph.microsoft.com/v1.0/users', headers=myHeaders) users_response.raise_for_status() users_data = users_response.json() print(users_data)
额外检查项
- 确认Azure AD应用已授予
User.Read.All应用权限,且已点击授予管理员同意(客户端凭证流必须需要管理员同意应用权限才能生效)。 - 检查租户ID
{myTenant}是否填写正确,可替换为租户域名或租户GUID。
内容的提问来源于stack exchange,提问作者Alan W
相关产品推荐
相关产品推荐

