Youtube API via Node.js QuickStart Authentication Error

Viewed 499

Google provides a tutorial online for how to connect to their API via node.js, which I am using for a Discord bot. Main issue is that it seems fairly outdated.

https://developers.google.com/youtube/v3/quickstart/nodejs

First issue was that they ask you to select an "Other" option which doesn't exist and has been replaced by "desktop app". Whatever, easy fix.

Main issue I'm having is with their quickstart.js code:

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the YouTube API.
  authorize(JSON.parse(content), getChannel);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
    if (err) throw err;
    console.log('Token stored to ' + TOKEN_PATH);
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function getChannel(auth) {
  var service = google.youtube('v3');
  service.channels.list({
    auth: auth,
    part: 'snippet,contentDetails,statistics',
    forUsername: 'GoogleDevelopers'
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var channels = response.data.items;
    if (channels.length == 0) {
      console.log('No channel found.');
    } else {
      console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
                  'it has %s views.',
                  channels[0].id,
                  channels[0].snippet.title,
                  channels[0].statistics.viewCount);
    }
  });
}

Below you can see that the console requests you to follow the URL to get a code. Doing so with the developer email that I used to create the OAuth brings me to a failure screen.

node quickstart.js
Authorize this app by visiting this url:  https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&response_type=code&client_id=645691957923-bsnq8pdtt4dcoprqolb5tovjp92ma718.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob
Enter the code from that page here:

Failure page

So I had to add my developer email as a test user and this allowed me to generate the code. Properly, which I then input into the console only to receive the following error:

node quickstart.js
Authorize this app by visiting this url:  https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&response_type=code&client_id=645691957923-bsnq8pdtt4dcoprqolb5tovjp92ma718.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob
Enter the code from that page here: <code went here>
Error while trying to retrieve access token GaxiosError: invalid_grant
    at Gaxios._request (E:\Carleton\Year4\Honors\node_modules\gaxios\build\src\gaxios.js:129:23)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async OAuth2Client.getTokenAsync (E:\Carleton\Year4\Honors\node_modules\google-auth-library\build\src\auth\oauth2client.js:124:21) {
  response: {
    config: {
      method: 'POST',
      url: 'https://oauth2.googleapis.com/token',
      data: 'code=4%2F1AX4XfWgjMdTQj5gcKCf76-HZowlr4Ohhz9Zn3Zg6B3i-MkCFVCP1qfV9F88&client_id=645691957923-bsnq8pdtt4dcoprqolb5tovjp92ma718.apps.googleusercontent.com&client_secret=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&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&grant_type=authorization_code&code_verifier=',
      headers: [Object],
      paramsSerializer: [Function: paramsSerializer],
      body: 'code=4%2F1AX4XfWgjMdTQj5gcKCf76-HZowlr4Ohhz9Zn3Zg6B3i-MkCFVCP1qfV9F88&client_id=645691957923-bsnq8pdtt4dcoprqolb5tovjp92ma718.apps.googleusercontent.com&client_secret=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&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&grant_type=authorization_code&code_verifier=',
      validateStatus: [Function: validateStatus],
      responseType: 'json'
    },
    data: { error: 'invalid_grant', error_description: 'Bad Request' },
    headers: {
      'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
      'cache-control': 'no-cache, no-store, max-age=0, must-revalidate',
      connection: 'close',
      'content-encoding': 'gzip',
      'content-type': 'application/json; charset=utf-8',
      date: 'Fri, 15 Oct 2021 17:18:58 GMT',
      expires: 'Mon, 01 Jan 1990 00:00:00 GMT',
      pragma: 'no-cache',
      server: 'scaffolding on HTTPServer2',
      'transfer-encoding': 'chunked',
      vary: 'Origin, X-Origin, Referer',
      'x-content-type-options': 'nosniff',
      'x-frame-options': 'SAMEORIGIN',
      'x-xss-protection': '0'
    },
    status: 400,
    statusText: 'Bad Request',
    request: { responseURL: 'https://oauth2.googleapis.com/token' }
  },
  config: {
    method: 'POST',
    url: 'https://oauth2.googleapis.com/token',
    data: 'code=4%2F1AX4XfWgjMdTQj5gcKCf76-HZowlr4Ohhz9Zn3Zg6B3i-MkCFVCP1qfV9F88&client_id=645691957923-bsnq8pdtt4dcoprqolb5tovjp92ma718.apps.googleusercontent.com&client_secret=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&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&grant_type=authorization_code&code_verifier=',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'User-Agent': 'google-api-nodejs-client/7.10.1',
      'x-goog-api-client': 'gl-node/16.9.1 auth/7.10.1',
      Accept: 'application/json'
    },
    paramsSerializer: [Function: paramsSerializer],
    body: 'code=4%2F1AX4XfWgjMdTQj5gcKCf76-HZowlr4Ohhz9Zn3Zg6B3i-MkCFVCP1qfV9F88&client_id=645691957923-bsnq8pdtt4dcoprqolb5tovjp92ma718.apps.googleusercontent.com&client_secret=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&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&grant_type=authorization_code&code_verifier=',
    validateStatus: [Function: validateStatus],
    responseType: 'json'
  },
  code: '400'
}

Does anyone have an idea what's causing this authentication issue? I'm new to interacting with the api. I figure I need some sort of added credentials that YouTube/Google are not explaining to me within the tutorial since it seems to be outdated.

2 Answers

invalid_grant can be a hard error to nail down lets start in order of most often the cause.

  1. Double check that you did create an installed application credentials. Yes should be desktop credentials.
  2. Check the time on your machine it must be in sync with NTP.
  3. Make sure you did not try to use the authorization code twice. It will only work once and it expires in less than five minutes.
  4. In the users google account under third party apps with access remove it completely there. Then try again.

Beyond that. I would double check what you are copying

code=4%2F1AX4XfWgjMdTQj5gcKCf76-HZowlr4Ohhz9Zn3Zg6B3i-MkCFVCP1qfV9F88

That 4% at the beginning looks strange to me.

The actual issue was kind of silly. The main problem was a mkdir error caused by an invalid pathname for the token.

var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';

If I ran the program again after I received the error, it would give me the new error I posted on the original question. This is because rerunning the program makes it require you to grab a new code from Google, which I didn't understand. SO the invalid grant came from an outdated code. The fix was to change the pathname to somewhere it could easily make a directory for the .credentials. Basically just make sure you grab a code every new run until you have your credentials / token stored.

Related