已配置Microsoft Graph API应用权限并获管理员同意,如何调用该API?
你已配置的Microsoft Graph应用权限如下图:
使用应用权限调用Microsoft Graph API的完整步骤
前置准备
先收集Azure AD应用注册的3个核心参数:
- 应用(客户端)ID
- 目录(租户)ID
- 客户端凭据(测试场景可用客户端密钥,生产环境推荐使用证书)
步骤1:请求访问令牌
应用权限场景使用客户端凭证流获取访问令牌,令牌有效期默认为1小时,过期后需要重新请求。
通用请求参数
请求地址:https://login.microsoftonline.com/{替换为你的租户ID}/oauth2/v2.0/token
请求体参数:
- grant_type:固定值
client_credentials - client_id:替换为你的应用客户端ID
- client_secret:替换为你生成的客户端密钥
- scope:固定值
https://graph.microsoft.com/.default
curl请求示例
curl --location --request POST 'https://login.microsoftonline.com/替换为你的租户ID/oauth2/v2.0/token' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'grant_type=client_credentials' \ --data-urlencode 'client_id=替换为你的应用客户端ID' \ --data-urlencode 'client_secret=替换为你的客户端密钥' \ --data-urlencode 'scope=https://graph.microsoft.com/.default'
请求成功后会返回包含access_token字段的响应,后续调用接口需要携带该令牌。
步骤2:携带令牌调用Graph接口
以调用获取租户内所有用户列表的接口为例,示例如下:
curl调用示例
curl --location --request GET 'https://graph.microsoft.com/v1.0/users' \ --header 'Authorization: Bearer 替换为你上一步获取的access_token'
Python调用示例
import requests # 获取访问令牌 tenant_id = "替换为你的租户ID" client_id = "替换为你的应用客户端ID" client_secret = "替换为你的客户端密钥" token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token" token_params = { "grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret, "scope": "https://graph.microsoft.com/.default" } token_resp = requests.post(token_url, data=token_params) access_token = token_resp.json()["access_token"] # 调用Graph接口 graph_url = "https://graph.microsoft.com/v1.0/users" headers = {"Authorization": f"Bearer {access_token}"} graph_resp = requests.get(graph_url, headers=headers) print(graph_resp.json())
注意事项
- 调用的接口需要和你已经授予的应用权限匹配,否则会返回403无权限错误
- 生产环境不要硬编码客户端密钥,建议存储到专业密钥管理服务中
- 可以在令牌到期前提前重新请求新令牌,避免调用接口时出现401未授权错误
内容的提问来源于stack exchange,提问作者asingh
相关产品推荐
相关产品推荐

