Google OAuth token exchange returns invalid_code

google-oauthoauth

I have been implementing the Google web server OAuth flow, but when I attempted to exchange the authorization code with access token, it always complains "invalid_code".

Here is the issue:

Step 1:

Redirect one of our pages to 'https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=https%3A%2F%2Fmyurl.com%2Fcallback&response_type=code&client_id=some_client_id'

Step 2:

The redirection happens and google would redirect to our url
https://myurl.com/callback?code=somecode

Step 3:

curl -X POST –data "code=somecode&client_id=some_client_id&some_client_secret=some_client_secret&redirect_uri=https://myurl.com/callback&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token -v –trace-ascii /dev/stout

The response comes back:

HTTP 400 Bad request

{
"error" : "invalid_grant",
"error_description" : "Invalid code."
}

Can someone help me with this issue? Thanks!

Best Answer

The life span of authorization code is only 10 mins,and can only be used one time. So do these checks:

  1. Do you use it 10 min later? If so, use it in 10 mins.
  2. Have you used it before? If so, obtain a new one and then use it.
  3. Is you server time in sync with Google OAuth server's? If not, change your time.
Related Topic