Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google OAuth 2 authorization - swapping code for token

I'm trying to implement Google OAuth 2 to get access to Google APIs. I follow this guide, using server-side scenario.

I have no problem with getting the code, server redirects to localhost (which is the only server allowed in redirect URIs for now). To achieve this, I go to https://accounts.google.com/o/oauth2/auth?client_id=whatever.apps.googleusercontent.com&redirect_uri=http://localhost/&scope=https://www.google.com/m8/feeds/&response_type=code page.

Then, I tried using curl (as in guide) to test, if Google's server responds with access token. However, it seems to fail very hard. Only response I can get is {"error":"invalid_client"}. I'm sure I provide everything Google wants me to provide - code, client ID, client secret, redirect URI (localhost) and grant_type=authorization_code.

Whole curl command line is:

curl https://accounts.google.com/o/oauth2/token -d "code=<code>&client_id=whatever.apps.googleusercontent.com&client_secret=<won't tell!>&redirect_uri=http://localhost&grant_type=authorization_code"

Am I missing something? How can I exchange code for access token?

like image 716
Dr McKay Avatar asked Apr 14 '11 19:04

Dr McKay


3 Answers

Did you urlencode your client secret and redirect url? That works for me.

Should be http%3A%2F%2Flocalhost instead of https://localhost.

like image 129
Kenan Avatar answered Sep 28 '22 02:09

Kenan


I had the same error until I realized that I was trying to connect with a client ID which I created for iOS. So for me the solution was to create a new API key-secret pair on the API Console with the platform set to "other".

Now I'm getting other errors but that's another story. ;)

like image 21
Lvsti Avatar answered Sep 28 '22 01:09

Lvsti


Happens when you use wrong Client secret. Make sure you are using correct Client secret from Google API console. I was using Email address since API console displays the information in the following order:

  1. Client ID
  2. Email address
  3. Client secret
like image 38
Nikola M. Avatar answered Sep 28 '22 00:09

Nikola M.