Retrieving Access Token for Service Account using Google Apps Script

Gists

This is a sample script for retrieving the access token for Service Account using Google Apps Script. The flow for using this script is as follows.

  1. At first, please create the Service Account and retrieve JSON file.
  2. Put Scopes, private_key and client_email to the script.
  3. Run the script.
var private_key = "#####"; // private_key of JSON file retrieved by creating Service Account
var client_email = "#####"; // client_email of JSON file retrieved by creating Service Account
var scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Scopes


var url = "https://www.googleapis.com/oauth2/v4/token";
var header = {
  alg: "RS256",
  typ: "JWT",
};
var now = Math.floor(Date.now() / 1000);
var claim = {
  iss: client_email,
  scope: scopes.join(" "),
  aud: url,
  exp: (now + 3600).toString(),
  iat: now.toString(),
};
var signature = Utilities.base64Encode(JSON.stringify(header)) + "." + Utilities.base64Encode(JSON.stringify(claim));
var jwt = signature + "." + Utilities.base64Encode(Utilities.computeRsaSha256Signature(signature, private_key));

var params = {
  method: "post",
  payload: {
    assertion: jwt,
    grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
  },
};
var res = UrlFetchApp.fetch(url, params).getContentText();
Logger.log(res);

Sample script

If the access token retrieved at above is used for retrieving file list, the sample script is as follows.

var u = "https://www.googleapis.com/drive/v3/files?access_token=" + JSON.parse(res).access_token;
var r = UrlFetchApp.fetch(u);
Logger.log(r)

References:

 Share!