Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Google Workspace Developers profile imageJustin Poehnelt
Justin Poehnelt forGoogle Workspace Developers

Posted on • Originally published atjustin.poehnelt.com on

     

Apps Script Service Account Impersonation

Unlike many other environments in Google Cloud that provide default application credentials, Apps Script is built on OAuth and user credentials. However there are many cases, where a service account is needed to access Google Cloud resources. For example, a service account is needed to interact with theGoogle Chat API as a Chat App.

Instead of downloading the service account key and storing it in the Apps Script project, the service account can be impersonated using theScriptApp.getOAuthToken() and user as principal. This allows the service account to be usedwithout downloading the key.

Setup service account impersonation and Apps Script

There a few steps to get this working right in Apps Script:

  1. Create a service account in the Google Cloud project
  2. Grant the principal (your account or whoever executes the script) access to the service account
  3. Add theService Account Token Creator role to the principal (Owner role is not sufficient)
  4. Enable theIAM Service Account Credentials API in the Google Cloud project
  5. Add the Google Cloud project number to the Apps Script project settings
  6. Add the following scopes to the Apps Script project manifest:
{"oauthScopes":["https://www.googleapis.com/auth/script.external_request","https://www.googleapis.com/auth/cloud-platform"]}
Enter fullscreen modeExit fullscreen mode

A more detailed explanation of these steps can be found in theCreate short-lived credentials for a service account.

IAM Service Account Credentials API and impersonation

To generate the OAuth token for the service account, thegenerateAccessToken endpoint of the IAM Credentials API is used. Calling this endpoint requires code similar to the following usingUrlFetchApp andScriptApp.getOAuthToken():

/** * Generates an access token using impersonation. Requires the following: * * - Service Account Token Creator * - IAM Credentials API * * @params {string} serviceAccountEmail * @params {Array<string>} scope * @params {string} [lifetime="3600s"] * @returns {string} */functiongenerateAccessTokenForServiceAccount(serviceAccountEmailOrId,scope,lifetime="3600s",// default){consthost="https://iamcredentials.googleapis.com";consturl=`${host}/v1/projects/-/serviceAccounts/${serviceAccountEmailOrId}:generateAccessToken`;constpayload={scope,lifetime,};constoptions={method:"POST",headers:{Authorization:"Bearer"+ScriptApp.getOAuthToken()},contentType:"application/json",muteHttpExceptions:true,payload:JSON.stringify(payload),};constresponse=UrlFetchApp.fetch(url,options);if(response.getResponseCode()<300){returnJSON.parse(response.getContentText()).accessToken;}else{thrownewError(response.getContentText());}}
Enter fullscreen modeExit fullscreen mode

This function can be used to generate an access token for the service account. The access token can then be used to make requests to Google Cloud APIs.

Generating and using service account access tokens in Apps Script

Now I can use this function to generate an access token for the service account and verify it contains valid scopes:

functionmain(){consttoken=generateAccessTokenForServiceAccount(// can also be the email: foo@your-project.iam.gserviceaccount.com"112304111718889638064",["https://www.googleapis.com/auth/datastore"]);// verify the tokenconsole.log(UrlFetchApp.fetch(`https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${token}`,).getContentText(),);}
Enter fullscreen modeExit fullscreen mode

The output looks like the following:

12:53:12 PM   Notice  Execution started12:53:13 PM   Info    ya29.c.c0AY_VpZ... // truncated12:53:13 PM   Info{"issued_to":"112304111718889638064","audience":"112304111718889638064","scope":"https://www.googleapis.com/auth/datastore","expires_in": 3599,"access_type":"online"}12:53:14 PM   Notice  Execution completed
Enter fullscreen modeExit fullscreen mode

To use this token to make requests to Google Cloud APIs, the token can be added to theAuthorization header of the request instead of theScriptApp.getOAuthToken() user token:

constoptions={headers:{Authorization:`Bearer${token}`},};UrlFetchApp.fetch(url,options);
Enter fullscreen modeExit fullscreen mode

Be sure to update the scopes in thegenerateAccessTokenForServiceAccount call to match the scopes needed for the request.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
max_ko_freelancer profile image
Max Kowald
  • Location
    World
  • Education
    University of applied science Wildau, Germany - Master of Sciene Business Computing
  • Joined

Thanks for your detailed guide. I would like to achieve the above but not linking my app script to one GCP. How would this be possible? Thanks for your answer in advance.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Need help with developing on Google Workspace? Check out our documentation.

More fromGoogle Workspace Developers

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp