Search code examples
node.jsgoogle-oauthgoogle-api-nodejs-client

Error: invalid_request getToken


Steps I have taken

Using Google's developper console:

  1. I have created a project and created a client for that project.
  2. I have activated Youtube API Data
  3. I set a the callback to http://localhost:3000/callback
  4. I have downloaded the "client_secrets".

Node server initial steps:

  1. Using "client_secrets" I have created a new OAuth2Client instance that I named oauth2Client
  2. I generated the URL with oauth2Client variable specifying the following:

var url = oauth2Client.generateAuthUrl({
            access_type: 'offline', //returns fresh token,
            scope: 'https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtubepartner'
        });

Google Authorization page:

  1. I go to the Generated URL and click authorize and get redirected to my callback on http://localhost:3000/callback

Node Server final steps:

  1. I get the "code" in the URL (looks something like this: 4/gZpLEwZWD6OVEE7F5uXXXXXXXXXXXXXXXXX )
  2. Using the same oauth2Client variable I attempt to get the token like so:

oauth2Client.getToken(code, function (err, tokens) {
    // set tokens to the client
    console.log('errors ' + err);
    console.log('tokens ' + tokens);
    oauth2Client.setCredentials(tokens);
})

The result from the console.log's are:

 errors Error: invalid_request
 tokens null

Question

What is causing the invalid_request? What part did I miss?


Some other similar questions propose different solutions

There seem to be quite a few questions on this subject, but most are specific questions with too often very vague answers. I'm asking a generic question and looking for a specific answer.


Solution

  • You didn't mention constructing of oauth2Client instance, so it can be a problem from lib issue on GutHub google-api-nodejs-client/issues/231

    Namely, the third argument in constructor OAuth2 is going be a string

    client_secrets.web.redirect_uris[0]
    

    var oauth2Client = new OAuth2Client(
     client_secrets.web.client_id, 
     client_secrets.web.client_secret, 
     client_secrets.web.redirect_uris[0] //<-- take first uri
    );