Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google OAuth token exchange returns invalid_code

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!

like image 284
oldmanwiggins Avatar asked Jun 02 '14 20:06

oldmanwiggins


People also ask

How long does OAuth token last Google?

The access token is set with a reasonably lower expiration time of 30 mins. The refresh token is set with a very long expiration time of 200 days.

What is OAuth2 token exchange?

The OAuth2 Token Exchange 8693 RFC defines a protocol for exchanging security tokens from OAuth2 authorisation servers. With a rising popularity of micro-service patterns, it's almost a given that the API you are calling is actually being fronted by a middleware service.

What is Google OAuth token?

The id_token is used in OpenID Connect protocol, where the user is authenticated as well as authorized. (There's an important distinction between authentication and authorization.) You will get id_token and access_token. The id_token value contains the information about the user's authentication.


2 Answers

I was using http://localhost:8080 as my redirect url since I was just trying out their examples. And my json file contents had this:

"redirect_uris": [
  "http://localhost:8080"
],
"javascript_origins": [
  "http://localhost:8080"
]

In the developer console I had the redirect_uri set to "http://localhost:8080" and I was getting the same error. I changed it to "http://localhost:8080/" and then it started working. (Essentially adding a '/' at the end.)

Hope this helps!

like image 196
nitarshs Avatar answered Oct 24 '22 10:10

nitarshs


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.
like image 28
Owen Cao Avatar answered Oct 24 '22 11:10

Owen Cao