Skip to content

Instantly share code, notes, and snippets.

@deniscanevaro
Forked from tanaikech/readme.md
Created December 7, 2018 11:57
Show Gist options
  • Save deniscanevaro/b570334c65a2b01b3ce75144b0a2c7ef to your computer and use it in GitHub Desktop.
Save deniscanevaro/b570334c65a2b01b3ce75144b0a2c7ef to your computer and use it in GitHub Desktop.
Retrieving Access Token for Service Account using Google Apps Script

Retrieving Access Token for Service Account using Google Apps Script

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/v3/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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment