Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created April 2, 2019 07:51
Show Gist options
  • Save tanaikech/7aaf2276e4e6104b89802e85957e75ae to your computer and use it in GitHub Desktop.
Save tanaikech/7aaf2276e4e6104b89802e85957e75ae to your computer and use it in GitHub Desktop.
Retrieving Access Token using Service Account for Node.js without using googleapis

Retrieving Access Token using Service Account for Node.js without using googleapis

This is a sample Node.js script to retrieve access token from Service Account of Google without using googleapis.

const cryptor = require('crypto');
const request = require('request');

const privateKey = "###"; // private_key of JSON file retrieved by creating Service Account
const clientEmail = "###"; // client_email of JSON file retrieved by creating Service Account
const scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Sample scope

const url = "https://www.googleapis.com/oauth2/v4/token";
const header = {
  alg: "RS256",
  typ: "JWT",
};
const now = Math.floor(Date.now() / 1000);
const claim = {
  iss: clientEmail,
  scope: scopes.join(" "),
  aud: url,
  exp: (now + 3600).toString(),
  iat: now.toString(),
};

const signature = Buffer.from(JSON.stringify(header)).toString('base64') + "." + Buffer.from(JSON.stringify(claim)).toString('base64');

var sign = cryptor.createSign('RSA-SHA256');
sign.update(signature);
const jwt = signature + "." + sign.sign(privateKey, 'base64');

request({
  method: "post",
  url: url,
  body: JSON.stringify({
    assertion: jwt,
    grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
  }),
}, (err, res, body) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(body);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment