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

Python实现个人版OneDrive身份认证报错问题求助

解决方案

错误根因梳理

第一种方案报错原因

  • 授权令牌的受众(audience)与请求端点不匹配:你使用的https://api.onedrive.com/v1.0端点要求令牌的scope必须包含OneDrive专属前缀,若你之前获取令牌时用的是Graph权限范围,就会触发认证失败。
  • 也可能是本地存储的令牌本身已过期、scope配置错误,导致权限校验不通过。

第二种方案报错原因

  • 权威节点配置错误:个人版Microsoft账户不能使用企业租户专属的授权端点,你当前填写的https://login.microsoftonline.com/UsadyProgimnasia.onmicrosoft.com是企业租户专属地址,必须改用面向个人用户的consumers或通用common端点。
  • 参数传递错误:调用acquire_token_silent时,你将本身已是列表类型的scopes又套了一层列表,导致权限识别异常。
  • 权限范围配置不合理:公开客户端使用授权码流时不需要使用.default后缀,直接指定具体权限即可。

可运行修正方案

第一步:先确认Azure应用配置

  1. 应用注册的支持账户类型选择个人Microsoft账户(或包含个人账号的通用类型)
  2. 重定向URI类型选择公共客户端(移动/桌面),值填写http://localhost/auth-response
  3. 不需要配置客户端密钥,公开客户端无需密钥即可认证。

第二步:修正后的MSAL代码示例

import hidden
from hidden import oauthr
import requests
import json
from msal import PublicClientApplication

client_id = oauthr()["consumer_key"]
# 明确指定需要的OneDrive操作权限
scopes = ['Files.ReadWrite.All']
redirect_uri = "http://localhost/auth-response"
code = oauthr()["code"]

# 1. 修正权威节点为个人账号专属的consumers端点
app = PublicClientApplication(
    client_id,
    authority="https://login.microsoftonline.com/consumers"
)
    
result = None
accounts = app.get_accounts()
if accounts:
    print("Pick the account you want to use to proceed:")
    for a in accounts:
        print(a["username"])
    chosen = accounts[0]
    # 2. 修正scopes参数,不要嵌套列表
    result = app.acquire_token_silent(scopes, account=chosen)

   
if not result:
    print('No suitable token exists in cache. Get a new one from Azure AD')
    result = app.acquire_token_by_authorization_code(code, scopes, redirect_uri=redirect_uri)
    if "access_token" in result:
        access_token = result["access_token"]
        print("获取令牌成功,尝试调用OneDrive接口:")
        # 3. 改用微软Graph接口请求OneDrive资源,兼容性更强
        root_url = "https://graph.microsoft.com/v1.0/me/drive/root"
        resp = requests.get(root_url, headers={"Authorization": f"Bearer {access_token}"})
        print(json.loads(resp.content))
    else:
        print(result.get("error"))
        print(result.get("error_description"))
        print(result.get("correlation_id"))

旧方案兼容调整(若坚持使用原OneDrive v1.0接口)

如果要保留第一种方案的请求端点,只需将获取令牌时的scope调整为https://api.onedrive.com/Files.ReadWrite.All,确保令牌受众与请求端点匹配即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:54:07