Create short-lived credentials for multiple service accounts

This page explains how to create short-lived credentials for a service accountbased on a delegation chain of service accounts. You can use this approach whenyou need to issue a series of token generation calls to obtain a token with thepermissions you need to accomplish your task.

After you get a short-lived credential, you can use it toimpersonate theservice account.

If you can generate a token with the required permissions with a single tokengeneration call, you shouldcreate short-lived credentials for that serviceaccount directly.

About creating short-lived credentials

Depending on the type of token you create, you can use short-lived credentialsto authenticate calls to Google APIs, third-party APIs, or applications thatrequire ID tokens. Short-lived credentials have a limited lifetime, withdurations of just a few hours or shorter, and are not automatically refreshed.Short-lived service account credentials are useful for scenarios where youneed to grant limited access to resources for trusted service accounts. Theyalso create less risk than long-lived credentials, such as service accountkeys.

You can create the following types of short-lived credentials for a serviceaccount:

  • OAuth 2.0 access tokens

    Access tokens are accepted for authentication by most Google APIs. When yougenerate an access token for a service account, the access token comeswithout a refresh token, which means that when the token expires, you mustrepeat the token creation process to generate a new one.

    For more information, seeAccess tokens.

  • OpenID Connect (OIDC) ID tokens

    ID tokens follow theOpenID Connect (OIDC) specification. ID tokens are accepted by a limited number of services and applications.

    For more information, seeID tokens andAuthentication for applications hosted on Cloud Run or Cloud Run functions.

  • Self-signed JSON Web Tokens (JWTs)

    You can use self-signed JWTs to authenticate to some Google APIs without getting an access token from the Authorization Server. APIs deployed with API Gateway require them.

  • Self-signed binary blobs

    Self-signed blobs are useful in scenarios when you need to securely transmit arbitrary binary data, usually for authentication purposes.

Delegated request flow

The delegated request flow lets you chaindirect requestsusing a single request, instead of needing to make several direct requests insequence. In this flow, the request for a service account credential isdelegated to one or more service accounts in adelegation chain beforegenerating a credential for the final service account. The resulting credentialonly represents the final service account, and not the intermediate serviceaccounts in the delegation chain.

Each service account in the delegation chain must havethe required permissions on the next service account in the chain, so that itcan pass along the request.

If one service account provides all of the permissions you need, you should usethe simpler flow described inCreate short-lived credentials from a service account.

Before you begin

  • Enable the IAM and Service Account Credentials APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the APIs

  • UnderstandIAM service accounts

  • If you haven't already, enable billing and the IAM API byfollowing the steps in thequickstart.

  • Identify the service accounts you will use in your delegation chain.

    You cancreate a new service accountand include it in the delegation chain if needed.

Provide required permissions

Adelegated request involves more than twoidentities: the caller, one or more service accounts in adelegation chain,and finally the service account for which a credential is created. In this flow,consider the following identities:

  • Service Account 1 (SA_1), the caller who issues arequest for the short-lived credentials.
  • Service Account 2 (SA_2), an intermediary serviceaccount that will delegate the initial request toSA_3. This account only passes on the request—itdoesn't giveSA_1 orSA_3 anyadditional access.
  • Service Account 3 (SA_3), the limited-privilegeaccount for whom the credential is created.

To allow delegation, each account must grant the Service Account Token Creatorrole (roles/iam.serviceAccountTokenCreator) to the previous account in thechain.

In this particular example,SA_1 must be granted theService Account Token Creator role (roles/iam.serviceAccountTokenCreator) onSA_2. This is an example of theSA_2 service account being treated as a resource: whenyou grant the role onSA_2, you update its allow policythe same way that you would update any other resource.

In this example flow, there is only one intermediary service account. Todelegate access through more than one service account, you must also assign thisrole to any other service account in the chain.

Next,SA_2 must also be granted the Service AccountToken Creator role (roles/iam.serviceAccountTokenCreator) onSA_3. This allowsSA_2 to createshort-lived credentials forSA_3.

The following steps use the REST API to grant the roles. However, you can alsouse the Google Cloud console or thegcloud CLI.

API

First, get the allow policy forSA_2 (theintermediary service account):

TheserviceAccounts.getIamPolicy method gets a service account's allow policy.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
  • SA_2: The name of Service Account 2.
  • POLICY_VERSION: The policy version to bereturned. Requests should specify the most recent policy version, which is policy version3. SeeSpecifyinga policy version when getting a policy for details.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_2@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy

Request JSON body:

{  "options": {    "requestedPolicyVersion":POLICY_VERSION  }}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_2@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_2@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy" | Select-Object -Expand Content

APIs Explorer (browser)

Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.

You should receive a JSON response similar to the following:

{  "version": 1,  "etag": "BwWKmjvelug=",  "bindings": [    {      "role": "roles/serviceAccountAdmin",      "members": [        "user:my-user@example.com"      ]    }  ]}

If you have not granted a role to the service account, the responsecontains only anetag value. Include thatetag value in the next step.

Next, modify the allow policy to grantSA_1 theService Account Token Creator role(roles/iam.serviceAccountTokenCreator).

For example, to modify the sample response from the previous step, add thefollowing:

{"version":1,"etag":"BwWKmjvelug=","bindings":[{"role":"roles/serviceAccountAdmin","members":["user:my-user@example.com"]},{"role":"roles/iam.serviceAccountTokenCreator","members":["serviceAccount:SA_1@PROJECT_ID.iam.gserviceaccount.com"]}]}

Then, write the updated allow policy forSA_2:

TheserviceAccounts.setIamPolicy method sets an updated allow policy for the service account.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
  • SA_2: The name of Service Account 2.
  • POLICY: A JSON representation of the policy that youwant to set. For more information about the format of a policy, see thePolicy reference.

    For example, to set the allow policy shown in the previous step, replacePOLICY with the following:

    {"version":1,"etag":"BwWKmjvelug=","bindings":[{"role":"roles/serviceAccountAdmin","members":["user:my-user@example.com"]},{"role":"roles/iam.serviceAccountTokenCreator","members":["serviceAccount:SA_1@PROJECT_ID.iam.gserviceaccount.com"]}]}

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_2@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy

Request JSON body:

{  "policy":POLICY}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_2@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_2@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy" | Select-Object -Expand Content

APIs Explorer (browser)

Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.

The response contains the updated allow policy.

Note: If you treat policies as code and store them in a version-control system, you should store the policy that is returned, not the policy that you sent in the request.

Now, get the allow policy forSA_3 (the serviceaccount for whom the credential is created):

TheserviceAccounts.getIamPolicy method gets a service account's allow policy.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
  • SA_3: The name of Service Account 3.
  • POLICY_VERSION: The policy version to bereturned. Requests should specify the most recent policy version, which is policy version3. SeeSpecifyinga policy version when getting a policy for details.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_3@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy

Request JSON body:

{  "options": {    "requestedPolicyVersion":POLICY_VERSION  }}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_3@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_3@PROJECT_ID.iam.gserviceaccount.com:getIamPolicy" | Select-Object -Expand Content

APIs Explorer (browser)

Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.

You should receive a JSON response similar to the following:

{  "version": 1,  "etag": "BwWKmjvelug=",  "bindings": [    {      "role": "roles/serviceAccountAdmin",      "members": [        "user:my-user@example.com"      ]    }  ]}

If you have not assigned a role to the service account, the responsecontains only anetag value. Include thatetag value in the next step.

Next, modify the allow policy to grantSA_2 theService Account Token Creator role (roles/iam.serviceAccountTokenCreator).

For example, to modify the sample response from the previous step, add thefollowing:

{"version":1,"etag":"BwWKmjvelug=","bindings":[{"role":"roles/serviceAccountAdmin","members":["user:my-user@example.com"]},{"role":"roles/iam.serviceAccountTokenCreator","members":["serviceAccount:SA_2@PROJECT_ID.iam.gserviceaccount.com"]}]}

Finally, write the updated allow policy:

TheserviceAccounts.setIamPolicy method sets an updated allow policy for the service account.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
  • SA_3: The name of Service Account 3.
  • POLICY: A JSON representation of the policy that youwant to set. For more information about the format of a policy, see thePolicy reference.

    For example, to set the allow policy shown in the previous step, replacePOLICY with the following:

    {"version":1,"etag":"BwWKmjvelug=","bindings":[{"role":"roles/serviceAccountAdmin","members":["user:my-user@example.com"]},{"role":"roles/iam.serviceAccountTokenCreator","members":["serviceAccount:SA_2@PROJECT_ID.iam.gserviceaccount.com"]}]}

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_3@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy

Request JSON body:

{  "policy":POLICY}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_3@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_3@PROJECT_ID.iam.gserviceaccount.com:setIamPolicy" | Select-Object -Expand Content

APIs Explorer (browser)

Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.

The response contains the updated allow policy.

Note: If you treat policies as code and store them in a version-control system, you should store the policy that is returned, not the policy that you sent in the request.

Request short-lived credentials

After you have granted the appropriate roles to each identity, you can requestshort-lived credentials for the desired service account. The followingcredential types are supported:

To understand how to specify a delegation chain for these requests,see theSpecifying a delegation chain sectionon this page.

Generate an OAuth 2.0 access token

By default, OAuth 2.0 access tokens are valid for a maximum of1 hour (3,600 seconds). However, youcan extend the maximum lifetime for these tokens to12 hours(43,200 seconds). To do so, identify the serviceaccounts that need an extended lifetime for tokens, thenadd these service accounts to an organization policythat includes theconstraints/iam.allowServiceAccountCredentialLifetimeExtension listconstraint. You can then specify a lifetime up to43,200 seconds when you create a token for theseservice accounts.

To generate an OAuth 2.0 access token for a service account, do the following:

API

The Service Account Credentials API'sserviceAccounts.generateAccessToken method generates an OAuth 2.0 access token for a service account.

Before using any of the request data, make the following replacements:

  • SA_NAME: The name of the service account that you want to create a token for.
  • PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
  • DELEGATES: If you are using adelegated request flow, seeSpecifying a delegation chain on this page.If you are using adirect request flow with no delegation, omitthedelegates field in the request body.
  • LIFETIME: The amount of time until the access token expires, in seconds. For example,300s.

    By default, the maximum token lifetime is 1 hour (3,600 seconds). To extend the maximum lifetime for these tokens to 12 hours (43,200 seconds), add the service account to an organization policy that includes theconstraints/iam.allowServiceAccountCredentialLifetimeExtension list constraint.

HTTP method and URL:

POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:generateAccessToken

Request JSON body:

{  "delegates": [DELEGATES  ],  "scope": [    "https://www.googleapis.com/auth/cloud-platform"  ],  "lifetime": "LIFETIME"}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:generateAccessToken"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:generateAccessToken" | Select-Object -Expand Content

APIs Explorer (browser)

Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.

If thegenerateAccessToken request was successful, the response body contains an OAuth 2.0 access token and an expiration time. TheaccessToken can then be used to authenticate a request on behalf of the service account until theexpireTime has been reached:

{  "accessToken": "eyJ0eXAi...NiJ9",  "expireTime": "2020-04-07T15:01:23.045123456Z"}

Generate OpenID Connect ID tokens

OpenID Connect ID tokens are valid for 1 hour(3,600 seconds). To generate an ID token for a serviceaccount, do the following:

API

The Service Account Credentials API'sserviceAccounts.generateIdToken method generates an OIDC ID token for a service account.

Before using any of the request data, make the following replacements:

  • PRIV_SA: The email address of the privilege-bearing service account for which the short-lived token is created.
  • AUDIENCE_NAME: The audience for the token, usually the URL of the application or service that the token will be used to access.

HTTP method and URL:

POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/PRIV_SA:generateIdToken

Request JSON body:

{  "audience": "AUDIENCE_NAME",  "includeEmail": "true"}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/PRIV_SA:generateIdToken"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/PRIV_SA:generateIdToken" | Select-Object -Expand Content

APIs Explorer (browser)

Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.

If thegenerateId request was successful, the response body contains an ID token that is valid for 1 hour. Thetoken can then be used to authenticate a request on behalf of the service account:

{  "token": "eyJ0eXAi...NiJ9"}

Create a self-signed JSON Web Token (JWT)

Self-signed JSON Web Tokens (JWTs) are useful in a variety of scenarios, suchas:

  • Authenticating a call to a Google API as described inGoogle's Authentication Guide.
  • Securely communicating between Google Cloud or non-Google services,such as App Engine applications. In this scenario, one application can signa token that can be verified by another application for authenticationpurposes.
  • Treating a service account as an identity provider by signing a JWT thatcontains arbitrary claims about a user, account, or device.

To generate a self-signed JWT for a service account, do the following:

API

The Service Account Credentials API'sserviceAccounts.signJwt method signs a JWT using a service account's system-managed private key.

Before using any of the request data, make the following replacements:

  • SA_NAME: The name of the service account that you want to create a token for.
  • PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
  • DELEGATES: If you are using adelegated request flow, seeSpecifying a delegation chain on this page.If you are using adirect request flow with no delegation, omitthedelegates field in the request body.
  • JWT_PAYLOAD: The JWT payload to sign, which is a JSON object that contains a JWT Claims Set. Include the claims that are necessary for your desired use case and to meet the validation requirements for the service you are calling. If you are calling a Google API, see Google's Authentication Guide for claim requirements.

    Theexp (expiration time) claim must be no more than 12 hours in the future. If you are calling a Google API, theexp claim must be set no more than 1 hour in the future.

    The following example payload contains claims to call a Google API, whereEXP is an integer timestamp representing the expiration time:

    {\"iss\": \"SA_NAME@PROJECT_ID.iam.gserviceaccount.com\", \"sub\": \"SA_NAME@PROJECT_ID.iam.gserviceaccount.com\", \"aud\": \"https://firestore.googleapis.com/\", \"iat\": 1529350000, \"exp\":EXP }

HTTP method and URL:

POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:signJwt

Request JSON body:

{  "delegates": [DELEGATES  ],  "payload": "JWT_PAYLOAD"}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:signJwt"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:signJwt" | Select-Object -Expand Content

APIs Explorer (browser)

Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.

If thesignJwt request was successful, the response body contains a signed JWT and the signing key ID that was used to sign the JWT. You can use thesignedJwt value as a bearer token to directly authenticate a request on behalf of the service account. The token is valid up to the expiration time specified in the request:

{  "keyId": "42ba1e...fc0a",  "signedJwt": "eyJ0eXAi...NiJ9"}

Create a self-signed blob

Self-signed blobs are useful in scenarios when you need to securely transmitarbitrary binary data, usually for authentication purposes. For example, ifyou want to use a custom protocol/token type (not JWT), you can include thatdata in a signed blob for use by a downstream service.

To generate a self-signed blob for a service account, do the following:

API

The Service Account Credentials API'sserviceAccounts.signBlob method signs a blob using a service account's system-managed private key.

Before using any of the request data, make the following replacements:

  • SA_NAME: The name of the service account that you want to create a token for.
  • PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
  • DELEGATES: If you are using adelegated request flow, seeSpecifying a delegation chain on this page.If you are using adirect request flow with no delegation, omitthedelegates field in the request body.
  • BLOB_PAYLOAD: A base64-encoded string of bytes. For example,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu.

HTTP method and URL:

POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:signBlob

Request JSON body:

{  "delegates": [DELEGATES  ],  "payload": "BLOB_PAYLOAD"}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:signBlob"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com:signBlob" | Select-Object -Expand Content

APIs Explorer (browser)

Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.

If thesignBlob request was successful, the response body contains a signed blob and the signing key ID that was used to sign the blob. You can use thesignedBlob value as a bearer token to directly authenticate a request on behalf of the service account. The token is valid until the service account's system-managed private key expires. This key's ID is the value of thekeyId field in the response.

{  "keyId": "42ba1e...fc0a",  "signedBlob": "eyJ0eXAi...NiJ9"}

Specify a delegation chain

When using adelegated request flow to createshort-lived service account credentials, the request body for each API mustspecify the service account delegation chain in the correct order and in thefollowing format:

projects/-/serviceAccounts/SA_ID

ReplaceSA_ID with either the service account's uniquenumeric ID or the service account's email address.

For example, in a delegation chain that flows fromSA_1(caller) toSA_2 (delegated) toSA_3 (delegated) toSA_4, thedelegates[] field would containSA_2 andSA_3 in the following order:

{"delegates":["projects/-/serviceAccounts/SA_2@PROJECT_ID.iam.gserviceaccount.com","projects/-/serviceAccounts/SA_3@PROJECT_ID.iam.gserviceaccount.com"]}

The caller and the service account for whom the credential is createdare not included in the delegation chain.

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 2025-12-09 UTC.