Google-api-nodejs-client: .getToken returning invalid_request

Created on 27 Jul 2014  ·  3Comments  ·  Source: googleapis/google-api-nodejs-client

I am getting an error each time I call getToken with a valid authCode. Here is the error log printed via the code below:

Error getting tokens:  invalid_request

Is there something wrong with the way I am using the APIs? Appreciate any pointers...

var express = require('express');
var router = express.Router();
var google = require('googleapis');
var urlshortener = google.urlshortener('v1');
var OAuth2 = google.auth.OAuth2;
var plus = google.plus('v1');
var googleClientInfo = { "web": {...} };
var oauth2 = new OAuth2(googleClientInfo.web.client_id, googleClientInfo.web.client_secret, googleClientInfo.web.redirect_uris);
var scopes = [  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/calendar'
];
google.options({ auth: oauth2 }); // set auth as a global default
var authUrl = oauth2.generateAuthUrl( {
  access_type: 'offline',
  scope: scopes
});

/* GET authCode from Google Server */
router.get('/', function(req, res) {
  console.log('Redirecting to URL: ' + JSON.stringify(authUrl));
  res.redirect(authUrl);
});

/* '/successful' is the redirect_uri with authCode query */
router.get('/successful', function(req, res) {
  console.log('Got code: ', (req.query.code));
  oauth2.getToken(req.query.code, function(err, tokens) {
    if(err) {
        console.log("Error getting tokens: ", err);
        res.redirect('/');
    } else {
        console.log("Saving tokens: ", JSON.stringify(tokens));
        // Save tokens
        oauth2.setCredentials(tokens);
        plus.people.get({ userId: 'me', auth: oauth2 }, function(err, response) {
          if(err) {
              console.log("Error getting userId: ", err);
              res.redirect('/');      
          } else {
              res.send('Login Successful: ' + JSON.stringify(response));
              console.log('Login Successful: ' + JSON.stringify(response));
          }
        });
    }
  });
});

module.exports = router;
triage me

Most helpful comment

Yes that works! Do you think its a good idea to throw an error if URI is an array? Would save debug time for a poor soul like me :). Thanks much for your help. Cheers.

All 3 comments

Update: I added some logging code in the oauth2client.js as follows:

/**
 * Gets the access token for given code.
 * @param {string} code The authorization code.
 * @param {function=} opt_callback Optional callback fn.
 */
OAuth2Client.prototype.getToken = function(code, opt_callback) {
  var uri = this.opts.tokenUrl || OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;
  var values = {
    code: code,
    client_id: this.clientId_,
    client_secret: this.clientSecret_,
    redirect_uri: this.redirectUri_,
    grant_type: 'authorization_code'
  };

 console.log("posting to uri: ", uri + ", with values: " + JSON.stringify(values));

  this.transporter.request({
    method: 'POST',
    uri: uri,
    form: values,
    json: true
  }, opt_callback);
};

I get the following logs (I've added a few ** to hide the user info

posting to uri:  https://accounts.google.com/o/oauth2/token, with 
values: {"code":"4/U2PMY1Gu6ImEuax57j9an7UoBBFa.or_RbQzmcKYZBrG_bnfDxpJe-8vsjgI", 
"client_id":"**********62-srmgmr0i8ck7j4vvi0454ntcfkoufgu1.apps.googleusercontent.com", 
"client_secret":"CdhVi3Yk21g_uswaDZafTeNC", 
"redirect_uri":["https://*********.herokuapp.com/googleLogin/successful"], 
"grant_type":"authorization_code"}

Error getting tokens:  invalid_request

The above looks okay but then why do I get a callback with err set to invalid_request? Something wrong with transporter perhaps?

What is the contents of googleClientInfo.web.redirect_uris ? Is it a string? If it's an Array, try specifying the first value in the array instead like googleClientInfo.web.redirect_uris[0]. If you're getting a valid authCode then I'm not sure if that would matter.

Perhaps you could try fooling with https://developers.google.com/oauthplayground/ and compare your requests with what requests your code is sending.

Yes that works! Do you think its a good idea to throw an error if URI is an array? Would save debug time for a poor soul like me :). Thanks much for your help. Cheers.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

joseparoli picture joseparoli  ·  3Comments

skiod picture skiod  ·  3Comments

CyberT33N picture CyberT33N  ·  3Comments

oliverjessner picture oliverjessner  ·  3Comments

streamnsight picture streamnsight  ·  4Comments