Copyright 2017-2024 Jason Ross, All Rights Reserved

Using the requests-oauthlib package in Python to obtain an OAuth2 token doesn’t always work. If you’re using the standard back-end example code and calling some APIs then you may receive an error that simply states:

“invalid_client”

The solution to this problem is fairly simple but can be hard to find, so how do you fix it?

The example code at https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow is:

from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
# client_id and client_secret are credentials obtained from your OAuth provider
client_id = 'your_client_id'
client_secret = 'your_client_secret'

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)

The error occurs in the oauth.fetch_token() call, even though the client_id and client_secret values are valid. This is because the API expects the client ID to be in the request body when the call is made to obtain the authorization token. By default the library assumes the API server is RFC-compliant, and so does not include the client ID in the request body. To force its inclusion, change the last line of the code above to include the include_client_id parameter, set to True:

token = oauth.fetch_token(token_url='https://provider.com/oauth2/token', client_id=client_id, include_client_id=True, client_secret=client_secret)

Once this is set, your client should be able to successfully retrieve the token it needs, and you can continue with your authorization process.

Made In YYC

Made In YYC
Made In YYC

Hosted in Canada by CanSpace Solutions