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.
- At first, please create the Service Account and retrieve JSON file.
- Put Scopes,
private_key
andclient_email
to the script. - 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);
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)