Getting 'invalid_grant' error with google oauth from second time
Asked Answered
T

2

6

I am using google oAuth for my python application in which I have feature to automatically logging in by google into my app. When I try to login first time, it will be successfull, but from next time if I will login it doesn't success and each time I gets 500 internal server error.

When I checked error logs, I got following error message on 'credentials = oAuthFlow.step2_exchange(code)' line

Failed to retrieve access token: {
    "error" : "invalid_grant"
}

I have valid clientId registered on google. Can anybody tell me why is it happening. I am using python 2.7.

Tortosa answered 30/8, 2013 at 10:58 Comment(0)
F
5

It could be caused by any number of things, including ...

  1. User has withdrawn permission
  2. The scopes have changed
  3. Google has retired your refresh token
  4. Bugs in your code which are presenting the wrong refresh token. Remember you will ONLY get a refresh token the first time through. On subsequent calls the refresh token will be null because you should have saved it in your database.

I get it a lot when I use the same user for both testing and live use since the two refresh tokens tend to overwrite each other.

The good news is that whatever the cause, the solution is always the same. You need to force a re-authorization from your user.

Fore answered 3/9, 2013 at 8:51 Comment(0)
S
0

This answer gives a very good overview of the many possible reasons for this issue. However in your specific case, which I was also suffering, where it was only broken from the second time of requesting a token after granting consent, I found that the issue was related to the code being returned in the query string from Google.

On the first time after granting consent it is returned as:

4/ABCDEFG123.....

On subsequent times it is returned as:

4%2FABCDEFG123.....

Where %2F can be decoded to /

To fix the issue if this is the case, URI decode the code that is returned using something like urllib.parse.unquote in Python or decodeURIComponent in Javascript.

Supervene answered 25/6 at 0:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.