Google Data Api returning an invalid access token

Posted by kingdavies on Stack Overflow See other posts from Stack Overflow or by kingdavies
Published on 2012-04-01T13:30:52Z Indexed on 2012/07/05 21:16 UTC
Read the original article Hit count: 213

Filed under:
|
|
|

I'm trying to pull a list of contacts from a google account. But Google returns a 401.

The url used for requesting an authorization code:

String codeUrl = 'https://accounts.google.com/o/oauth2/auth' + '?'
           + 'client_id=' + EncodingUtil.urlEncode(CLIENT_ID, 'UTF-8')
           + '&redirect_uri=' + EncodingUtil.urlEncode(MY_URL, 'UTF-8')
           + '&scope=' + EncodingUtil.urlEncode('https://www.google.com/m8/feeds/', 'UTF-8')
           + '&access_type=' + 'offline'
           + '&response_type=' + EncodingUtil.urlEncode('code', 'UTF-8')
           + '&approval_prompt=' + EncodingUtil.urlEncode('force', 'UTF-8');

Exchanging the returned authorization code for an access token (and refresh token):

String params = 'code=' + EncodingUtil.urlEncode(authCode, 'UTF-8')
              + '&client_id=' + EncodingUtil.urlEncode(CLIENT_ID, 'UTF-8')
              + '&client_secret=' + EncodingUtil.urlEncode(CLIENT_SECRET, 'UTF-8')
              + '&redirect_uri=' + EncodingUtil.urlEncode(MY_URL, 'UTF-8')      
              + '&grant_type=' + EncodingUtil.urlEncode('authorization_code', 'UTF-8');  

Http con = new Http();
Httprequest req = new Httprequest();
req.setEndpoint('https://accounts.google.com/o/oauth2/token');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');                   
req.setBody(params);
req.setMethod('POST');
Httpresponse reply = con.send(req); 

Which returns a JSON array with what looks like a valid access token:

{ 
    "access_token" : "{access_token}", 
    "token_type" : "Bearer", 
    "expires_in" : 3600, 
    "refresh_token" : "{refresh_token}" 
} 

However when I try and use the access token (either in code or curl) Google returns a 401:

curl -H "Authorization: Bearer {access_token}"  https://www.google.com/m8/feeds/contacts/default/full/

Incidentally the same curl command but with an access token acquired via https://code.google.com/oauthplayground/ works. Which leads me to believe there is something wrong with the exchanging authorization code for access token request as the returned access token does not work.

I should add this is all within the expires_in time frame so its not that the access_token has expired

© Stack Overflow or respective owner

Related posts about java

Related posts about google