使用Microsoft Graph API应用权限读取Outlook邮件遇服务主体缺失错误
解决Microsoft Graph API调用报错:客户端应用缺少服务主体
问题原因
你注册的是多租户应用,但目标租户(即代码中指定的tenant_id对应的租户,或你要访问的邮箱所属租户)尚未创建该应用的服务主体。多租户应用不会自动在所有租户生成服务主体,必须通过租户授权或手动添加来完成创建。
解决方案
方法1:完成租户管理员授权
构造授权URL,让目标租户的管理员访问并同意权限,系统会自动在该租户创建服务主体:
https://login.microsoftonline.com/{目标租户ID}/adminconsent?client_id={你的client_id}&scope=https://graph.microsoft.com/.default
替换{目标租户ID}为代码中使用的tenant_id,{你的client_id}为应用注册时的客户端ID,管理员登录后确认授权即可。
方法2:手动创建服务主体
- 切换到目标租户(代码中
tenant_id对应的Microsoft Entra ID租户) - 进入「企业应用程序」→「所有应用程序」→「新建应用程序」
- 选择「从库中添加应用程序」,搜索你的多租户应用名称并添加
- 添加完成后,该应用的服务主体会自动在当前租户生成
额外检查项
- 确认代码中的
tenant_id是你要访问的邮箱所属租户的ID,而非应用注册时的租户ID - 在应用注册的「API权限」页面,点击「授予管理员同意」,确保权限已针对目标租户生效
调整后的示例代码
import msal import requests client_id = "你的client_id" tenant_id = "目标租户ID" client_secret = "你的client_secret" authority = f"https://login.microsoftonline.com/{tenant_id}/" scopes = ["https://graph.microsoft.com/.default"] app = msal.ConfidentialClientApplication(client_id, client_credential=client_secret, authority=authority) result = app.acquire_token_for_client(scopes=scopes) if "access_token" in result: access_token = result["access_token"] headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } # 确保邮箱属于指定的目标租户 endpoint = "https://graph.microsoft.com/v1.0/users/目标邮箱@xxx.com/messages" response = requests.get(endpoint, headers=headers) if response.status_code == 200: print("邮件列表:", response.json()) else: print(f"请求错误: {response.status_code}, {response.json()}") else: print(f"获取令牌失败: {result.get('error_description')}")
内容的提问来源于stack exchange,提问作者user13
相关产品推荐
相关产品推荐

