How to create access tokens with domain-wide delegation in GSuite using Node.js

With domain-wide delegation we can generate access tokens to act on behalf of GSuite users. This post shows you how.

Please read my previous post to learn about setting up domain-wide delegation and creating a service account key.

With a service account key in place, here’s how to get an access token.

// loads credentials from .env file
require("dotenv").config();
import { google } from "googleapis";

const requestOauthToken = () => {
  // use credentials from service account key.
  const client_email = process.env.GOOGLE_CLIENT_EMAIL;
  const private_key = process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n");
  // some user that you want to act on behalf of.
  const emailToImpersonate = "some-user@acme-industries.com";
  const jwtClient = new google.auth.JWT(
    client_email,
    null,
    private_key,
    // add one or more scopes to grant access to resources like GDrive.
    ["https://www.googleapis.com/auth/drive"],
    emailToImpersonate
  );
  return jwtClient.authorize();
};

// an example of how access tokens are retrieved.
const main = async () => {
  try {
    const token = await requestOauthToken();
    console.log({ token, access_token: token.access_token });
  } catch (e) {
    console.error("Failed to get token", e);
  }
};

main();

As you can see, the authentication process is very similar to my previous post. The main difference is that we call jwtClient.authorize() to retrieve the token. Interestingly, this was not well documented anywhere when I searched. Luckily, I stumbled on a similar example deep in a Github issue.

If this helped you out, please give me a shoutout on Twitter. :)