requests_oauthlib BackendClient获取OAuth2令牌报错:需提供code或授权响应
使用requests_oauthlib的BackendApplicationClient获取OAuth2令牌时抛出ValueError错误
问题描述
我尝试用requests_oauthlib的BackendApplicationClient工作流建立OAuth2.0连接,对应的PowerShell代码可以正常运行,但Python代码调用fetch_token()时抛出如下错误:
token = session.fetch_token(token_url=tokenURL, client_id=ClientID, client_secret=secret) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\1455765990E\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests_oauthlib\oauth2_session.py", line 251, in fetch_token raise ValueError( ValueError: Please supply either code or authorization_response parameters.
后端应用工作流不需要授权响应URL,而且code应该是fetch_token返回的结果,我当前并未持有该参数,这个错误不符合预期。
可正常运行的PowerShell代码
function GetToken($secret) { $uri = $LoginURL + $tenant + '/oauth2/v2.0/token' $body = @{ "client_id" = $ClientID "scope" = "https://dod-graph.microsoft.us/.default" "username" = $tenant "password" = $client_secret "grant_type" = "client_credentials" "client_secret" = $secret } $response = Invoke-RestMethod -Uri $uri -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded' return $response $token = $response.access_token $exp = $response.expires_in $token }
问题Python代码
def getToken(store): """ Get OAUTH Token and session""" tokenURL = LoginURL + TenantID + '/oauth2/v2.0/token' scope = "https://dod-graph.microsoft.us/.default" client = oauthlib.oauth2.BackendApplicationClient(client_id=ClientID, scope=scope) session = requests_oauthlib.OAuth2Session(client) session.verify = False secret = store['secret'] print(f"--token URL: {tokenURL}") token = session.fetch_token(token_url=tokenURL, client_id=ClientID, client_secret=secret) print(f"--token: {token}") return session
解决方案
修改fetch_token方法的调用,明确指定grant_type为"client_credentials",同时传递scope参数:
def getToken(store): """ Get OAUTH Token and session""" tokenURL = LoginURL + TenantID + '/oauth2/v2.0/token' scope = "https://dod-graph.microsoft.us/.default" client = oauthlib.oauth2.BackendApplicationClient(client_id=ClientID) session = requests_oauthlib.OAuth2Session(client) session.verify = False secret = store['secret'] print(f"--token URL: {tokenURL}") token = session.fetch_token( token_url=tokenURL, client_id=ClientID, client_secret=secret, scope=scope, grant_type="client_credentials" ) print(f"--token: {token}") return session
原因说明
你的PowerShell代码显式设置了grant_type=client_credentials,但默认情况下fetch_token会默认使用授权码流程,因此会要求传入code或authorization_response参数。通过显式指定grant_type="client_credentials",可以让requests_oauthlib切换到客户端凭证流程,匹配后端应用工作流的要求。同时传递scope参数也能确保请求符合OAuth2服务端的校验规则。
另外,创建BackendApplicationClient时无需传递scope,将其放到fetch_token中传递更符合方法设计逻辑。
内容的提问来源于stack exchange,提问作者Dr.YSG
相关产品推荐
相关产品推荐

