AuthorizationCodeCredential.get_token失败:Session.request()参数异常求助
问题场景
使用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
相关产品推荐
相关产品推荐

