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

Python程序通过Client ID连接Sharepoint REST API遇令牌错误求助

解决Python连接Sharepoint REST API的认证错误

你遇到的Cannot get binary security token for from https://login.microsoftonline.com/extSTS.srf错误,本质是使用了过时的STS认证方式,现代Sharepoint(尤其是Online版本)已不再推荐这种认证,或是认证参数配置不全导致无法获取安全令牌。下面是两种主流的正确连接方案:

方案1:使用用户名密码认证(无MFA场景)

推荐使用office365-rest-python-client库进行快速对接,步骤如下:

  1. 安装依赖库
pip install office365-rest-python-client
  1. 编写连接代码
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential

# 替换为你的实际信息
site_url = "https://你的公司域名.sharepoint.com/sites/目标站点名"
username = "你的工作账号@公司域名.com"
password = "你的账号密码"

# 初始化客户端上下文
ctx = ClientContext(site_url).with_credentials(UserCredential(username, password))

# 测试连接:获取站点标题
web = ctx.web.get().execute_query()
print(f"当前站点标题: {web.properties['Title']}")

方案2:设备码认证(开启MFA场景)

如果你的账号启用了多因素认证,需要通过Azure AD注册应用并使用设备码认证:

  1. 安装依赖库(同方案1)
  2. 编写连接代码
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.device_code_provider import DeviceCodeProvider

# 替换为你的实际信息
site_url = "https://你的公司域名.sharepoint.com/sites/目标站点名"
client_id = "你的Azure AD应用客户端ID"  # 需要在Azure AD后台注册应用获取

# 初始化认证提供者
provider = DeviceCodeProvider(client_id)
ctx = ClientContext(site_url).with_credentials(provider)

# 执行认证:控制台会输出设备码和验证链接,需在浏览器中完成验证
ctx.execute_query()

# 测试连接
web = ctx.web.get().execute_query()
print(f"当前站点标题: {web.properties['Title']}")

本地Sharepoint服务器连接(NTLM认证)

如果是公司内部本地部署的Sharepoint,可使用NTLM认证方式:

from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.authentication_context import AuthenticationContext

site_url = "http://本地Sharepoint站点地址"
ctx_auth = AuthenticationContext(site_url)
if ctx_auth.acquire_token_for_user("本地域账号", "账号密码"):
    ctx = ClientContext(site_url, ctx_auth)
    web = ctx.web.get().execute_query()
    print(f"当前站点标题: {web.properties['Title']}")
else:
    print("认证失败:", ctx_auth.get_last_error())

错误排查提示

  • 确认账号拥有目标Sharepoint站点的访问权限
  • 检查网络是否能正常访问微软认证服务器(login.microsoftonline.com)
  • 不要使用已被淘汰的extSTS.srf端点进行认证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:31:11