Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active May 19, 2021
Embed
What would you like to do?
Retrieving Access Token for Service Account using Javascript

Retrieving Access Token for Service Account using Javascript

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.

const u = `https://www.googleapis.com/drive/v3/files?access_token=${obj.access_token}`;
const r = await fetch(u)
  .then((res) => res.json())
  .catch((err) => console.log(err));
console.log(r);

References

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