Python requests_oauthlib OAUTH V2 BackendCleint fetch_token()错误

t3psigkw  于 2023-08-02  发布在  Python
关注(0)|答案(1)|浏览(103)

我正在尝试使用BackendClient工作流创建OATH V2.0连接。使用requests_oauthlib包。文档位于:https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow
代码在PowerShell中运行良好,但Python中的等效代码给出错误:

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是没有意义的(因为这是一个后端工作流),代码是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

inn6fuwd

inn6fuwd1#

requests_oauthlib.OAuth2Session的第一个位置参数是client_id(str),但您传递了BackendApplicationClient,因此在调用期间会话客户端是None,当它是none时,requests_oauthlib将使用WebApplicationClient作为默认值。
要解决这个问题,只需通过关键字参数传递客户端:

# --- snip ---
client = oauthlib.oauth2.BackendApplicationClient(client_id=ClientID, scope=scope)
session = requests_oauthlib.OAuth2Session(client=client)
# --- snip ---

字符串

相关问题