gpt4 book ai didi

python - 如何使用授权类型为 'Client Credentials' 的请求 OAuthlib ?

转载 作者:行者123 更新时间:2023-12-01 07:18:05 30 4
gpt4 key购买 nike

因此,我尝试调用一个 API,该 API 在文档中提供 token URL。为此,我想使用 python requests 包中的 OAuthlib。当我查看their docs时他们举了这个例子:

# Credentials you get from registering a new application
client_id = '<the id you get from github>'
client_secret = '<the secret you get from github>'

# OAuth endpoints given in the GitHub API documentation
authorization_base_url = 'https://github.com/login/oauth/authorize'
token_url = 'https://github.com/login/oauth/access_token'

from requests_oauthlib import OAuth2Session
github = OAuth2Session(client_id)

# Redirect user to GitHub for authorization
authorization_url, state = github.authorization_url(authorization_base_url)
print ('Please go here and authorize,', authorization_url)

# Get the authorization verifier code from the callback url
redirect_response = input('Paste the full redirect URL here:')

# Fetch the access token
github.fetch_token(token_url, client_secret=client_secret,
authorization_response=redirect_response)

# Fetch a protected resource, i.e. user profile
r = github.get('https://api.github.com/user')
print (r.content)

但在 API 文档中该服务仅提供 token url。它给出了这个 Http Body POST示例:

Method: POST
Host: https://login.bol.com/token
Content-Type: application/x-www-form-urlencoded
Accept: application/json

Body: client_id=oRNWbHFXtAECmhnZmEndcjLIaSKbRMVE&client_secret= MaQHPOnmYkPZNgeRziPnQyyOJYytUbcFBVJBvbMKoDdpPqaZbaOiLUTWzPAkpPsZFZbJHrcoltdgpZolyNcgvvBaKcmkqFjucFzXhDONTsPAtHHyccQlLUZpkOuywMiOycDWcCySFsgpDiyGnCWCZJkNTtVdPxbSUTWVIFQiUxaPDYDXRQAVVTbSVZArAZkaLDLOoOvPzxSdhnkkJWzlQDkqsXNKfAIgAldrmyfROSyCGMCfvzdQdUQEaYZTPEoA&grant_type=client_credentials

或者这个 HTTP header POST示例:

Method: POST
Host: https://login.bol.com/token?grant_type=client_credentials
Accept: application/json
Authorization: Basic <credentials>

哪里<credentials><client_id>:<client_secret> 的串联.

如何通过此 API 使用请求 OAuthlib?因为API docs不要声明任何授权基础 URL。

最佳答案

我想你可以提供<client_id>:<client_secret>像这样:

from oauthlib.oauth2 import BackendApplicationClient
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url='https://provider.com/oauth2/token', client_id=client_id,
client_secret=client_secret)

参见this

关于python - 如何使用授权类型为 'Client Credentials' 的请求 OAuthlib ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57848095/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com