Accesstoken

Retrieving Access Token using Service Account for PHP without using googleapis

Gists

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

Sample script

<?php

$private_key = "-----BEGIN PRIVATE KEY-----\n###-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account
$client_email = "###"; // client_email of JSON file retrieved by creating Service Account
$scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Sample scope

$url = "https://www.googleapis.com/oauth2/v4/token";
$header = array("alg" => "RS256", "typ" => "JWT");
$now = floor(time());
$claim = array(
	"iss" => $client_email,
	"sub" => $client_email,
	"scope" => implode(" ", $scopes),
	"aud" => $url,
	"exp" => (string)($now + 3600),
	"iat" => (string)$now,
);
$signature = base64_encode(json_encode($header, JSON_UNESCAPED_SLASHES)) . "." . base64_encode(json_encode($claim, JSON_UNESCAPED_SLASHES));
$b = "";
openssl_sign($signature, $b, $private_key, "SHA256");
$jwt = $signature . "." . base64_encode($b);
$curl_handle = curl_init();
curl_setopt_array($curl_handle, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => array(
        "assertion" => $jwt,
        "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer"
    ),
]);
$res = curl_exec($curl_handle);
curl_close($curl_handle);
$obj = json_decode($res);
$accessToken = $obj -> {'access_token'};
print($accessToken . "\n");

// This is the script for testing the access token. The file list of the service account's Drive is retrieved using Drive API.
$curl_test = curl_init();
curl_setopt($curl_test, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files?access_token=' . $accessToken);
curl_setopt($curl_test, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl_test);
print($response);

?>

References

Retrieving Access Token for Service Account using Javascript

Gists

This is a sample script for retrieving the access token for Service Account using Javascript. 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.

Sample script

In this script, 2 libraries of jsencrypt and crypto-js are used.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/3.0.0-rc.1/jsencrypt.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

<script>
  async function sample() {
    const private_key = "###"; // private_key of JSON file retrieved by creating Service Account
    const client_email = "###"; // client_email of JSON file retrieved by creating Service Account
    const scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Scopes

    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: client_email,
      scope: scopes.join(" "),
      aud: url,
      exp: (now + 3600).toString(),
      iat: now.toString(),
    };
    const signature =
      btoa(JSON.stringify(header)) + "." + btoa(JSON.stringify(claim));
    const sign = new JSEncrypt();
    sign.setPrivateKey(private_key);
    const jwt =
      signature + "." + sign.sign(signature, CryptoJS.SHA256, "sha256");
    const params = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        assertion: jwt,
        grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
      }),
    };
    const obj = await fetch(url, params)
      .then((res) => res.json())
      .catch((err) => console.log(err));
    console.log(obj);
  }

  sample();
</script>

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

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

Gists

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);
});

Retrieving Access Token using Service Account by Google's OAuth2 package for Golang

Gists

This is a sample golang script for retrieving access token using Service Account of Google by Google’s OAuth2 package.

The script without using Google’s OAuth2 package is here.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"

    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "golang.org/x/oauth2/jwt"
)

func serviceAccount(credentialFile string) (*oauth2.Token, error) {
    b, err := ioutil.ReadFile(credentialFile)
    if err != nil {
        return nil, err
    }
    var c = struct {
        Email      string `json:"client_email"`
        PrivateKey string `json:"private_key"`
    }{}
    json.Unmarshal(b, &c)
    config := &jwt.Config{
        Email:      c.Email,
        PrivateKey: []byte(c.PrivateKey),
        Scopes: []string{
            "https://www.googleapis.com/auth/drive.metadata.readonly",
        },
        TokenURL: google.JWTTokenURL,
    }
    token, err := config.TokenSource(oauth2.NoContext).Token()
    if err != nil {
        return nil, err
    }
    return token, nil
}

func main() {
    token, err := serviceAccount("credentials.json") // Please set here
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(res)
}

Retrieving Access Token for Service Account using Google Apps Script

Gists

Updated on June 22, 2024

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.

Usage

  1. Create the Service Account and retrieve JSON file.
  2. Put Scopes, private_key and client_email as an object.
  • If you want to use impersonate email, please set the value of impersonate_email.
  1. Run the script.
/**
 * ### Description
 * Get access token from service account.
 * ref: https://tanaikech.github.io/2018/12/07/retrieving-access-token-for-service-account-using-google-apps-script/
 *
 * @param {Object} object Object including private_key, client_email, impersonate_email.
 * @param {String} object.private_key
 * @param {String} object.client_email
 * @param {String} object.impersonate_email
 * @param {Array} object.scopes
 * @returns {String} Access token.
 */
function getAccessTokenFromServiceAccount_(object) {
  const { private_key, client_email, impersonate_email = "", scopes = [] } = object;
  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: client_email, scope: scopes.join(" "), aud: url, exp: (now + 3600).toString(), iat: now.toString() };
  if (impersonate_email != "") {
    claim.sub = impersonate_email;
  }
  const signature = Utilities.base64Encode(JSON.stringify(header)) + "." + Utilities.base64Encode(JSON.stringify(claim));
  const jwt = signature + "." + Utilities.base64Encode(Utilities.computeRsaSha256Signature(signature, private_key));
  const params = { payload: { assertion: jwt, grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer" } };
  const res = UrlFetchApp.fetch(url, params);
  const { access_token } = JSON.parse(res.getContentText());
  return access_token;
}


// Please run this script.
function main() {
  const object = {
    private_key: "-----BEGIN PRIVATE KEY-----\n###-----END PRIVATE KEY-----\n",
    client_email: "###",
    // impersonate_email: "###", // If you want to use an impersonate email, please set this.
    scopes: ["###", "###",,,],
  };
  const accessToken = getAccessTokenFromServiceAccount_(object);
  console.log(accessToken);
}

Sample script

When you can obtain the access token by the above script, you can also use the following sample script. The following sample script retrieves the file list of the drive of the service account with Method: files.list of Drive API v3.

Directly Using Access Token by googleapis for Node.js

Gists

This sample script is for directly using the refreshed access token by googleapis for Node.js. When oauth2Client.refreshAccessToken((err, tokens) => {}); is used to retrieve the refreshed access token, the following error occurs.

DeprecationWarning: The refreshAccess Token method has been deprecated, and will be removed in the 3.0 release of goo gle-auth-library. Please use the getRequestHeaders method instead.

It is required to use getRequestHeaders(). But I couldn’t find the sample script using getRequestHeaders(). So I created this sample script. If this was useful for you, I’m glad.

Remove Third-party Apps with Account Access using Google Apps Script

Gists

Overview

This is a method for removing Third-party Apps with Account Access using a script.

Demo

Description

When users create a script in a project and run the script, if the methods which are required to use scopes are included, users have to authorize to use the scopes using the browser. By authorizing it, users can use the script. The authorized projects can be seen at Third-party Apps with Account Access. One day, I had a situation that it required to remove the authorization of project, because of the security. Third-party Apps with Account Access can be manually removed as you know. But at that time, I wanted to remove using a script. So I came up with this method.