【问题标题】:How to use the Requests OAuthlib with grant-type 'Client Credentials'?如何使用带有授权类型“客户端凭据”的请求 OAuthlib?
【发布时间】:2020-01-10 20:54:52
【问题描述】:

所以我尝试调用 在文档中提供令牌 url 的 API。为此,我想使用 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 文档中,该服务仅提供令牌 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 头 POST 例子:

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

其中&lt;credentials&gt;&lt;client_id&gt;:&lt;client_secret&gt; 的串联。

如何通过此 API 使用请求 OAuthlib?因为API docs 没有说明任何授权基础网址。

【问题讨论】:

    标签: python oauth oauth-2.0 python-requests


    【解决方案1】:

    我认为您可以像这样提供&lt;client_id&gt;:&lt;client_secret&gt;

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 2020-02-25
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 2016-06-05
      • 2018-11-09
      相关资源
      最近更新 更多