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

无Azure CLI环境下,如何获取服务主体令牌用于Microsoft Graph API?

解决方法:获取适用于Microsoft Graph API的服务主体令牌

问题根源

你之前的curl请求无法获取可用令牌,核心原因是**resource参数指定的是Azure CLI专属的资源标识符**(2ff814a6-3304-4ab8-85cb-cd0e6f879c1d),而Microsoft Graph API需要匹配自身的资源范围,导致令牌权限不兼容。

正确的令牌获取命令

兼容OAuth 2.0 v1端点(与原请求格式一致)

将resource参数替换为Microsoft Graph的官方资源标识符https://graph.microsoft.com,执行以下命令:

curl -X POST \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=<azure_client_id>&resource=https://graph.microsoft.com&client_secret=<azure_client_secret>" \
  https://login.microsoftonline.com/<tenant_id>/oauth2/token

推荐:使用OAuth 2.0 v2端点(现代标准)

如果偏好v2协议,将resource替换为scope参数,指定Graph API的默认权限范围(对应服务主体已配置的所有权限):

curl -X POST \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=<azure_client_id>&scope=https://graph.microsoft.com/.default&client_secret=<azure_client_secret>" \
  https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/token

令牌使用与验证

  1. 执行命令后,从返回的JSON响应中提取access_token字段。
  2. 用该令牌调用Microsoft Graph API,示例:
curl -X GET \
  -H "Authorization: Bearer <auth-token>" \
  https://graph.microsoft.com/beta/groups

关键注意事项

  • 确保你的服务主体已被授予Microsoft Graph API的对应权限(例如Group.Read.All),且该权限已得到管理员同意,否则会返回权限不足的错误。
  • 替换命令中所有占位符(<tenant_id>、<azure_client_id>等)为实际值。

内容的提问来源于stack exchange,提问作者Joost Dübken

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:55:04