Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created December 7, 2018 03:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tanaikech/20ea127a8e23a7c609f8d764c8b7ed7c to your computer and use it in GitHub Desktop.
Save tanaikech/20ea127a8e23a7c609f8d764c8b7ed7c 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:

@deniscanevaro
Copy link

Excelente

@majestique
Copy link

The url is updated to v4 now: https://www.googleapis.com/oauth2/v4/token
If you need to impersonate email (for scoped/secured access) you'll need:

var claim = {
  iss: client_email,
  sub:  "yourimpersonate@email.com",
  scope: scopes.join(" "),
  aud: url,
  exp: (now + 3600).toString(),
  iat: now.toString(),
};

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