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

Python脚本连接Office共享邮箱遇权限问题求助

解决Microsoft Graph API访问Office共享邮箱的403权限错误

问题背景

开发Python脚本连接Office共享邮箱,通过Microsoft Graph API生成访问令牌,但调用接口时返回403权限不足错误(错误码Authorization_RequestDenied)。此前尝试IMAP4_SSL方案也出现LOGIN失败问题。已在Entra创建应用并配置必要ID,同时启用了应用权限和委派权限,最终确认是误用委派权限而非应用权限,修正后问题解决。

相关代码

import msal
import json
import requests
import creds as c
import logging


tenant_id = c.tenant_id
authority = f'https://login.microsoftonline.com/{c.tenant_id}'
client_id = c.client_id
client_secret = c.secret
scope = ['https://graph.microsoft.com/.default']
app = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret)
result = app.acquire_token_silent(scopes=scope, account=None)

if not result:
    logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
    result = app.acquire_token_for_client(scopes=scope)

if "access_token" in result:
    graph_data = requests.get(
        #'https://graph.microsoft.com/v1.0/users',
        headers={'Authorization': 'Bearer ' + result['access_token']},
        url=f'https://graph.microsoft.com/v1.0/users/{c.user_id}/messages').json()
    print("Graph API call result: ")
    print(json.dumps(graph_data, indent=2))
else:
    print(result.get("error"))
    print(result.get("error_description"))
    print(result.get("correlation_id"))

错误输出

错误: 403, {"error":{"code":"Authorization_RequestDenied","message":"权限不足,无法完成操作。"

解码后的令牌信息

aud: https://graph.microsoft.com
iss: https://sts.windows.net/8b6b7804-1008-4f7d-b866-65d2e04d0a63/
iat: 1701244213
nbf: 1701244213
exp: 1701248113
aio: E2VgYFhmyFf87vTS8D+uYt8jTvmzAgA=
app_displayname: Redmine Informatique
appid: 1cb255a3-4211-4bba-a741-8158331c26e9
appidacr: 1
idp: https://sts.windows.net/8b6b7804-1008-4f7d-b866-65d2e04d0a63/
idtyp: app
aud: 752e091f-2a92-4838-ab77-ab3b03953d73
rh: 0.AQwABHhriwgQfU-4ZmXS4E0KYwMAAAAAAAAAwAAAAAAAAACWAAA.
sub: 752e091f-2a92-4838-ab77-ab3b03953d73
tenant_region_scope: EU
tid: 8b6b7804-1008-4f7d-b866-65d2e04d0a63
uti: ZUgikoxms0a32rCuFh5OAg
ver: 1.0
wids: ['0997a1d0-0d1d-4acb-b408-d5ca73121e90']
xms_tcdt: 1426243296
xms_tdbr: EU

解决方案

  • 当前代码使用acquire_token_for_client获取令牌,属于客户端凭据流,该模式要求应用配置应用权限(Application),而非委派权限(Delegated)
  • 修正操作:在Entra应用管理界面中,移除不必要的委派权限,添加对应邮箱操作的应用权限(如Mail.Read、Mail.ReadWrite等),并完成管理员权限同意

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:12:40