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

通过Access Token连接Microsoft Graph时提示令牌为空的问题求助

问题分析与解决

核心错误点

你的代码存在两个关键问题,导致令牌无法正确传递:

  1. 获取Token时的参数结构错误:将请求头字段(Content-Type、Host)放入了请求体payload中,而非单独的请求头参数;同时urllib3提交表单格式的POST请求需用fields参数,而非直接传字典作为payload。
  2. 调用Graph API时的请求头传递错误:将Authorization请求头放入了payload(请求体)中,GET请求的请求头必须通过headers参数传递,payload仅用于POST/PUT等带请求体的请求。

修正后的代码

1. 获取Access Token的正确代码

import urllib3
import json

uri = "https://login.microsoftonline.com/companyID/oauth2/v2.0/token"

# 仅存放表单请求参数,不含请求头
form_data = {
    'client_id': 'xxxxxxxxxxxxxxxxxxxxx',
    'scope': 'https://graph.microsoft.com/.default',
    'client_secret': 'xxxxxxxxxxxxxxxxxxxxx',
    'grant_type': 'client_credentials'
}

# 单独定义请求头
headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host': 'login.microsoftonline.com'
}

http = urllib3.PoolManager()
# 使用fields参数传递表单数据,urllib3会自动处理编码
response = http.request('POST', uri, fields=form_data, headers=headers)

# 用json.loads替代eval,避免代码注入风险
response_data = json.loads(response.data.decode('utf-8'))
token = f"{response_data['token_type']} {response_data['access_token']}"

2. 调用Microsoft Graph API的正确代码

import urllib3

uri2 = 'https://graph.microsoft.com/v1.0/users/12345678-73a6-4952-a53a-e9916737ff7f'

# 请求头通过headers参数传递,GET请求无需payload
headers2 = {
    'Authorization': token,
    'Host': 'graph.microsoft.com'
}

http = urllib3.PoolManager()
# 传递headers参数而非payload
response2 = http.request('GET', uri2, headers=headers2)
print(response2.data.decode('utf-8'))

额外注意事项

  • 禁止使用eval()解析JSON响应,json.loads()是更安全的替代方案。
  • 确认应用已配置对应的应用权限(非委派权限),且权限已获得管理员同意。

内容的提问来源于stack exchange,提问作者jackrabbit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:45:17