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

AuthorizationCodeCredential.get_token失败:Session.request()参数异常求助

解决AuthorizationCodeCredential刷新令牌时的client_secret参数错误

问题场景

使用Azure Identity的AuthorizationCodeCredential配合Microsoft Graph Python SDK实现Web应用授权码流程,访问令牌过期后发起请求触发以下错误:

AuthorizationCodeCredential.get_token failed: Session.request() got an unexpected keyword argument 'client_secret'

预期令牌过期时Graph客户端能自动通过刷新令牌获取新访问令牌,但未实现。

解决方案

1. 使用异步凭据类适配异步框架

代码基于异步FastAPI框架,同步版AuthorizationCodeCredential在异步环境下刷新令牌时易出现参数传递异常。需替换为异步版AsyncAuthorizationCodeCredential,先安装异步依赖:

pip install azure-identity[aiohttp]

2. 调整凭据与客户端初始化代码

将同步凭据类替换为异步版本,并确保Graph客户端适配异步调用:

from azure.identity.aio import AsyncAuthorizationCodeCredential
from msgraph import GraphServiceClient

@app.post('/callback',status_code=201)
async def auth_code_callback(code:Annotated[str,Form()]):     
    # 注意:全局变量不适用于多用户场景,建议改用会话存储(如Redis)
    global graph_client,credentials     

    scopes = ['offline_access','Files.Read','User.Read']

    credentials = AsyncAuthorizationCodeCredential(
        client_id='7dddfa04-a853-47cd-8c92-d9b657992cec',
        tenant_id='common',
        authorization_code=code,
        redirect_uri='http://localhost:3000/callback',  
        client_secret='ynL8Q~L2qmt1y04ZBgA1h_h9_nlPiS4kqE46hac2'
    )
    
    graph_client = GraphServiceClient(credentials=credentials, scopes=scopes)

    return {'message':'Authorization successful'}

3. 确保SDK版本兼容

升级到最新稳定版SDK,避免版本不兼容导致的异常:

pip install --upgrade azure-identity msgraph-sdk

4. 优化凭据存储方式

全局变量graph_client和credentials在多用户场景下会导致凭据冲突,建议将用户凭据存储在会话(如FastAPI的Session或Redis)中,根据请求关联的用户身份获取对应凭据。

错误原因说明

错误提示显示刷新令牌时,代码错误地将client_secret传递给Session.request()方法,该方法并不接受此参数。这是同步凭据类在异步环境中调用时的适配问题,改用异步版凭据类可解决参数传递错误,同时确保令牌刷新流程正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 13:27:10