'Google API invalid_grant / bad_request

Using python 3.6, requests==2.22.0

Trying to use the Google API, in particular mobile and desktop apps flow

I am able to generate an auth code by using this url:

url = (
    'https://accounts.google.com/o/oauth2/v2/auth?'
    'scope=email%20profile&'
    'response_type=code&'
    'redirect_uri={redirect_uri}&'
    'client_id={client_id}&'
    'access_type=offline'.format(
        redirect_uri=redirect_uri,
        client_id=client_id,
    )
)

The redirect_uri I am using (for now) is simply https://google.com, and it is registered in the developer app I generated, in the Authorized redirect URIs section and in the Authorized domains section under the OAuth consent settings page/tab.

Once I paste the produced url in the browser - I get a code that I can extract and use to make the next call, which currently fails.

I made sure to replace "%2F" with "/" (when using Firefox).

Next, I am generating the data, and making the call to replace the code with the tokens:

data = {
    'client_id': client_id,
    'client_secret': client_secret,
    'grant_type': 'authorization_code',
    'code': code,
    'redirect_uri': redirect_uri,
}
url = 'https://oauth2.googleapis.com/token'

response = requests.post(
    url,
    data=data,
    headers={
        'Content-Type': 'application/x-www-form-urlencoded',
    },

print(response)
print(response.json())

The output:

<Response [400]>
{'error': 'invalid_grant', 'error_description': 'Bad Request'}


Solution 1:[1]

It's a two year-old issue but just for the sake of those came in here looking for an answer. I run into the same problem @camelBack did, the way I solve was kind of simple. I delete the credentials and run the authorization flow again. With new credentials.storage in place the problem went away. More info @ https://developers.google.com/identity/protocols/oauth2

An additional note for those struggling with the auth flow, one thing I realized after a lot of testing is that you need to run outside Jupyter Notebook. Open a terminal and run Python natively with the script. It should work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FCastell