简体   繁体   中英

Google Data Api returning an invalid access token

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

Ok so the problem was in the scope when requesting an authorization code. I had accidentally set the scope to be https://www.google.com/m8/feeds/contacts/default/full (the url for retrieving all contacts), the perils of late night coding. Ironically as the example in the question used the correct hard coded url it did not have the error. I'll leave the question in the hope that those having a similar problem will find it and the code in the question works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM