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

Python读取Sharepoint Excel时适配两步认证解决AADSTS53003错误

解决SharePoint Python访问时的两步认证(MFA)问题

你遇到的AADSTS53003错误,是因为当前使用的纯用户名密码认证流不支持两步认证(MFA),而企业的条件访问策略强制要求MFA,因此这种认证方式被拦截。

要集成两步认证,推荐使用设备代码流(Device Code Flow),这种方式支持通过Microsoft Authenticator应用批准登录请求,以下是具体实现步骤:

1. 准备依赖库

安装所需的Python库:

pip install msal office365-rest-python-client

2. 在Azure AD注册公共客户端应用

要使用设备代码流,需要先在Azure AD中注册一个公共客户端应用:

  • 登录Azure门户,进入Azure Active Directory -> 应用注册 -> 新注册
  • 填写应用名称,账户类型选择「仅此组织目录中的账户」(企业内部场景)
  • 重定向URI选择「公共客户端/native (mobile & desktop)」,填入http://localhost
  • 注册完成后,复制应用程序(客户端)ID(后续代码中用client_id)
  • 进入API权限,添加SharePoint的应用权限(如Sites.Read.All),并让管理员完成权限同意

3. 实现认证与文件访问代码

from office365.sharepoint.client_context import ClientContext
from msal import PublicClientApplication

# 配置参数
tenant_id = "你的租户ID"  # 可填企业域名,例如 COMPANY.onmicrosoft.com
client_id = "你的Azure应用客户端ID"
site_url = "https://COMPANY.sharepoint.com/sites/XXXX"
file_path = "/Shared Documents/XXX.xlsx"

# 初始化MSAL客户端
app = PublicClientApplication(
    client_id,
    authority=f"https://login.microsoftonline.com/{tenant_id}"
)

# 启动设备代码流
scopes = ["https://COMPANY.sharepoint.com/.default"]
device_flow = app.initiate_device_flow(scopes=scopes)
if "user_code" not in device_flow:
    raise ValueError(f"初始化设备流失败: {str(device_flow)}")

# 打印操作提示
print(device_flow["message"])

# 等待用户完成MFA验证并获取token
auth_result = app.acquire_token_by_device_flow(device_flow)

if "access_token" in auth_result:
    # 创建SharePoint客户端上下文
    ctx = ClientContext(site_url).with_access_token(auth_result["access_token"])
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()
    print(f"认证成功,当前站点: {web.properties['Title']}")

    # 获取目标Excel文件
    target_file = ctx.web.get_file_by_server_relative_url(file_path)
    ctx.load(target_file)
    ctx.execute_query()
    print(f"已定位文件: {target_file.properties['Name']}")

    # 后续可添加读取Excel内容的逻辑,例如将文件下载到本地再处理
    # with open("local_file.xlsx", "wb") as f:
    #     target_file.download(f)
else:
    print(f"认证失败: {auth_result.get('error_description', '未知错误')}")

代码说明

运行代码后,控制台会输出一个验证链接和验证码:

  1. 打开链接并输入验证码
  2. 在手机端的Microsoft Authenticator应用中批准登录请求
  3. 代码会自动获取有效访问令牌,完成SharePoint认证并访问目标文件

这种方式符合企业的条件访问策略,支持两步认证,替代了原来不支持MFA的纯密码认证流。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:52:38