Programming

【GAS×GCP】Obtaining an Access Token

Overview

When executing GCP APIs from GAS, an access token may be required.
In this session, we'll provide a hands-on walkthrough from obtaining an access token to retrieving a list of users registered in GCP.

By the way, Sorry for the most images are in Japanese in advance.

Account Registration

First, let's create a GCP account and set up a project!
The following article may be helpful for creating an account.

Once you've created the project, the next step is to set up a service account!

Creating a Service Account

Let's create a service account, which is required to obtain an access token from GCP.
In the GCP Console, go to the menu and select "IAM & Admin" → "Service Accounts".

Click the "Create Service Account" button at the top of the screen.

Enter a name for the service account. For this example, we'll use account as the name.
The Service Account ID and Description fields are optional, so you can fill them in as you like. Once you're done, click the "Create and Continue" button.

For the Role, set it to Basic → Owner. After assigning the role, click the "Done" button at the bottom of the screen.

That's it! The service account has now been created.
Make sure to take note of the service account's email address displayed in the Email column, as you'll need it later.
Click on the email address link to navigate to the account details page.

In the account details page, go to the "Keys" tab. Click "Add Key" → "Create New Key".

When prompted, choose JSON as the key format and download the generated file.

Open the downloaded JSON file and locate the value for private_key. Keep this value handy as you'll need it later.

In the GCP Console, use the search bar to look for "Cloud Resource Manager API" and select it.

Enable the API for your project.

Now you're ready to proceed with the next steps!

Coding

Below is the code to obtain an access token for GAS (the access token's expiration time is set to 30 minutes).

function getAccessToken() {
  const options = {
    "method": "POST",
    "payload": {
      "grant_type": 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      "assertion": getAssertion()
    },
    'muteHttpExceptions': true,
  };
  const response = JSON.parse(UrlFetchApp.fetch('https://oauth2.googleapis.com/token', options));
  return response.access_token;
}

function getAssertion() {
  const privateKey = "-----BEGIN PRIVATE KEY-----\n<PRIVATE KEY>-----END PRIVATE KEY-----\n"
  const header = {
    alg: 'RS256',
    typ: 'JWT'
  };
  const now = new Date();
  const claimSet = {
    iss: "<Service Account Mail>",
    scope: "https://www.googleapis.com/auth/cloud-platform.read-only",
    aud: "https://accounts.google.com/o/oauth2/token",
    exp: (now.getTime() / 1000) + 3000,
    iat: now.getTime() / 1000
  };
  let toSign = Utilities.base64EncodeWebSafe(JSON.stringify(header)) + '.' + Utilities.base64EncodeWebSafe(JSON.stringify(claimSet));
  toSign = toSign.replace(/=+$/, '');
  const signatureBytes = Utilities.computeRsaSha256Signature(toSign, privateKey);
  let signature = Utilities.base64EncodeWebSafe(signatureBytes);
  signature = signature.replace(/=+$/, '');
  return toSign + '.' + signature;
};

Next, using the access token above, we will execute the following API to retrieve GCP policies.
Additionally, the value of "scope" set in the getAssertion function of the above code is taken from the Authorization Scopes listed at the link below.

feedbackMethod: projects.get - GCP API

function getGcpPolicies() {
  const options = {
    "method": "POST",
    "contentType": "application/json",
    "headers": {
      "Authorization": "Bearer " + getAccessToken(),
    },
    'muteHttpExceptions': true,
  };
  const response = JSON.parse(UrlFetchApp.fetch('https://cloudresourcemanager.googleapis.com/v1/projects/<プロジェクトID>:getIamPolicy', options).getContentText());
  const policies = response.bindings;
  console.log(policies)
}

When you run the above, you should be able to confirm roles and the users associated with those roles, as shown below!
(Note: Deleted service accounts are also displayed.)

Summary

In this article, we explained how to obtain the access token needed to use GCP APIs with GAS.
We hope this article will be helpful when performing operations on Google Cloud from GAS!

Sponsored Link

  • Author

kaz

Full-stack Engineer specializing in Backend/Frontend/Cloud Infrastructure | Digital Nomad since June 2023, traveling the world | Sharing programming tips and insights | Posting travel updates on X

-Programming
-,