Authenticate as an Apps Script project using service accounts Stay organized with collections Save and categorize content based on your preferences.
This guide explains how to authenticate with a service account when calling APIsin Apps Script.
A service account is a special kind of account used by an application, ratherthan a person. You can use a service account to access data or perform actionsby the robot account, or to access data on behalf of Google Workspaceor Cloud Identity users. For more information, seeUnderstanding service accounts.For an overview about authentication for Google Workspace APIs, seeCreate access credentials.
When to use service accounts in Apps Script
Here are some reasons that you might consider using service accountauthentication instead of other authentication methods such asScriptApp.getOAuthToken():
- Better performance with Google Cloud APIs and services: ManyGoogle Cloud APIs are designed for service account authentication.Service accounts can also provide a more integrated, reliable, and secureway to interact with most APIs.
- Decoupled permissions: Service accounts have theirown permissions, separate from any user. The authentication method
ScriptApp.getOAuthToken()can fail when you share theApps Script project with other users. By using serviceaccounts, you can share scripts andpublish them as Google Workspace add-ons. - Automated scripts and long-running tasks: Service accounts let you runautomated scripts, batch processes, or background tasks without user input.
- Enhanced security and principle of least privilege: You can grantservice accounts specific permissions, providing access only to theresources they need. This follows theprinciple of least privilege,which lowers security risks. Using
ScriptApp.getOAuthToken()often grantsa script all user permissions, which can be too broad. - Centralized access management: Service accounts are managedusing Google Cloud'sIdentity and Access Management (IAM).IAM can help Google Workspace organizations manage access toauthenticated services within Apps Script projects.
Prerequisites
- AGoogle Cloud project.
- In your Cloud project,enable any APIs that you want toauthenticate with using service account credentials.
- Toassign roles to service accounts, you must havesuper administratorprivileges.
Create a service account
In your Cloud project, create a service account:
Google Cloud console
- In the Google Cloud console, go to Menu>IAM & Admin>Service Accounts.
- ClickCreate service account.
- Fill in the service account details, then clickCreate and continue.Note: By default, Google creates a unique service account ID. If you would like to change the ID, modify the ID in the service account ID field.
- Optional: Assign roles to your service account to grant access to your Google Cloud project's resources. For more details, refer toGranting, changing, and revoking access to resources.
- ClickContinue.
- Optional: Enter users or groups that can manage and perform actions with this service account. For more details, refer toManaging service account impersonation.
- ClickDone. Make a note of the email address for the service account.
gcloud CLI
- Create the service account:
gcloud iam service-accounts createSERVICE_ACCOUNT_NAME\ --display-name="SERVICE_ACCOUNT_NAME" - Optional: Assign roles to your service account to grant access to your Google Cloud project's resources. For more details, refer toGranting, changing, and revoking access to resources.
Assign a role to the service account
You must assign a prebuilt or custom role to a service account by a superadministrator account.
In the Google Admin console, go to Menu>Account>Admin roles.
Point to the role that you want to assign, and then clickAssign admin.
ClickAssign service accounts.
Enter the email address of the service account.
ClickAdd> Assign role.
Create credentials for a service account
You need to obtain credentials in the form of a public/private key pair. Thesecredentials are used by your code to authorize service account actions withinyour app.To obtain credentials for your service account:
- In the Google Cloud console, go to Menu>IAM & Admin>Service Accounts.
- Select your service account.
- ClickKeys>Add key>Create new key.
- SelectJSON, then clickCreate.
Your new public/private key pair is generated and downloaded to your machine as a new file. Save the downloaded JSON file as
credentials.jsonin your working directory. This file is the only copy of this key. For information about how to store your key securely, seeManaging service account keys. - ClickClose.
Copy the Cloud project number
- In the Google Cloud console, go to Menu>IAM & Admin>Settings.
- In theProject number field, copy the value.
Set up service account authentication in your Apps Script project
This section explains how to add your service account credentials from yourCloud project to an Apps Script project.
Set your Cloud project in Apps Script
Go to Apps Script to open or create a project:
In your Apps Script project,clickProject Settings
.
UnderGoogle Cloud Platform (GCP) Project, clickChange project.
InGCP project number, paste the Google Cloud project number.
ClickSet project.
Save the credentials as a script property
Securely store your service account credentials by savingthem as ascript property in yourApps Script project settings:
- Copy the contents of your service account JSON file (
credentials.json)that you created in theprevious section. - In your Apps Script project, go toProject Settings.
- From theProject Settings page, go toScript Properties and clickAdd script property and enter the following:
- In theProperty field, enter
SERVICE_ACCOUNT_KEY. - In theValue field, paste the content of your JSON key file.
- In theProperty field, enter
- ClickSave script properties.
Add the OAuth2 library
To handle the OAuth2 authentication flow, you can use theApps Script libraryapps-script-oauth2.
To add the library to your Apps Script project:
- In the Apps Script editor, at the left, next toLibraries, clickAdd a library.
- In theScript ID field, enter
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF. - ClickLook up.
- Select the latest version, and then clickAdd.
Call an API using service account credentials
To use the service account credentials from your Apps Scriptproject, you can use the following functiongetServiceAccountService():
/** * Get a new OAuth2 service for a given service account. */functiongetServiceAccountService(){constserviceAccountKeyString=PropertiesService.getScriptProperties().getProperty('SERVICE_ACCOUNT_KEY');if(!serviceAccountKeyString){thrownewError('SERVICE_ACCOUNT_KEY property is not set. '+'Please follow the setup instructions.');}constserviceAccountKey=JSON.parse(serviceAccountKeyString);constCLIENT_EMAIL=serviceAccountKey.client_email;constPRIVATE_KEY=serviceAccountKey.private_key;// Replace with the specific scopes required for your API.constSCOPES=['SCOPE'];returnOAuth2.createService('ServiceAccount').setTokenUrl('https://oauth2.googleapis.com/token').setPrivateKey(PRIVATE_KEY).setIssuer(CLIENT_EMAIL).setPropertyStore(PropertiesService.getScriptProperties()).setScope(SCOPES);}ReplaceSCOPE with theauthorization scope that you need to callthe API. The script uses the service account credentials that you savedas aSERVICE_ACCOUNT_KEY script property in theprevious step.
You can then use these credentials to call an API, as shown in the followingexample with theUrlFetch service:
functioncallApi(){constservice=getServiceAccountService();// TODO(developer): Replace with the payloadconstpayload={};// TODO(developer): Replace with the API endpointconstresponse=UrlFetchApp.fetch('API_URL',{method:'post',headers:{'Authorization':`Bearer${service.getAccessToken()}`,'Content-Type':'application/json',},payload:payload,});constresult=JSON.parse(response.getContentText());returnresult;}ReplaceAPI_URL with the HTTP endpoint that you arecalling.
Related topics
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-01-07 UTC.