Python requests_oauthlib OAUTH V2 BackendClient fetch_token()错误

n9vozmp4  于 2023-10-15  发布在  Python
关注(0)|答案(1)|浏览(64)

我正在尝试使用BackendClient工作流创建OAUTH 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
stszievb

stszievb1#

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

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

相关问题