Search code examples
pythonoauthoauth-2.0python-requests

How to use the Requests OAuthlib with grant-type 'Client Credentials'?


So I try to call an API which only provides an token url in the docs. For this I want to use the OAuthlib from the python requests package. When I view at their docs they give this example:

# 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)

But in the API documentation the service only provides the token url. It gives this Http Body POST example:

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

Or this HTTP header POST example:

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

Where <credentials> is a concatenation of <client_id>:<client_secret> .

How can I use the requests OAuthlib with this API? Because the API docs dont state any authorization base url.


Solution

  • I think you can provide <client_id>:<client_secret> like this:

    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)
    

    see this