Create short-lived credentials for a service account

Stay organized with collections Save and categorize content based on your preferences.

This page explains how to impersonate a service account by creating short-lived credentials for that service account.

Some system architectures are designed around privilege-bearing service accounts, which are designed to be used together. In this case, you might need to create your credentials for multiple service accounts.

About creating short-lived credentials

Service accounts can use short-lived credentials to authenticate calls to Google Cloud APIs, other Google APIs, and non-Google APIs. Short-lived credentials have a limited lifetime, with durations of just a few hours or shorter. Short-lived service account credentials are useful for scenarios where you need to grant limited access to resources for trusted service accounts. They also create less risk than long-lived credentials, such as service account keys.

Short-lived credentials can be represented as OAuth 2.0 access tokens, OpenID Connect ID tokens, self-signed JSON Web Tokens (JWTs), and self-signed binary objects (blobs). The most commonly used credential types are OAuth 2.0 access tokens and OpenID Connect (OIDC) ID tokens. You might use each type of token in the following scenarios:

  • OAuth 2.0 access token: An OAuth 2.0 access token is useful for authenticating access from a service account to Google Cloud APIs. Consider the following example use case: to get elevated permissions on a project, an administrator can create an OAuth 2.0 access token that belongs to a service account, then use that token to impersonate the service account when calling Google Cloud APIs. The token has a short lifetime so that the elevated permissions are temporary. Using short-lived tokens helps you implement the principle of least privilege across your identities and resources. It can also be useful when there is an emergency in a production environment, and an administrator needs a short-term elevated authorization for debugging.
  • OIDC ID token: An OIDC ID token is useful for authenticating the identity of a service account to services that accept OpenID Connect. Consider the following example use case: by creating an OIDC ID token belonging to a service account, a workload running on Google Cloud can authenticate itself to another workload deployed on a third-party cloud provider, such as a data pipeline job. If the target service is configured with OIDC, then authentication will succeed.

Direct request flow

When you create short-lived credentials for a service account using a direct request flow, the caller makes a direct request to create short-lived credentials. Two identities are involved in this flow: the caller, and the service account for which the credential is created.

If your system architecture is designed around tiers of limited-privilege service accounts, see Create short-lived credentials for multiple service accounts.

Before you begin

  • Enable the IAM and Service Account Credentials APIs.

    Enable the APIs

  • Understand IAM service accounts

  • If you haven't already, enable billing and the IAM API by following the steps in the Quickstart.

Provide required permissions

A direct request involves two identities: the caller, and the service account for which the credential is created. How you set up the permissions depends on whether the caller is using a service account or user credentials.

If you want to run the samples on this page in a local development environment, you would use user credentials. For production use, such as an application running on Compute Engine, you would use a service account to represent the caller.

Provide required permissions for a user account

When you want to use the Google Cloud CLI to generate short-lived tokens, or you want to generate short-lived tokens from a local development environment, you can use a user account to generate the tokens. Often, you can use your own Google Account.

When you use a user account to generate short-lived tokens, the following identities are involved:

  • Caller Google Account (CALLER_ACCOUNT)

    This user account is used to generate short-lived credentials for the privilege-bearing service account.

  • Privilege-bearing service account (PRIV_SA)

    This service account is granted the IAM roles needed for the short-lived token. This is the service account for which the short-lived token is created.

To enable CALLER_ACCOUNT to create short-lived credentials for PRIV_SA, you grant CALLER_ACCOUNT the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator) on PRIV_SA.

Console

  1. In the Google Cloud console, go to the Service Accounts page.

    Go to Service Accounts

  2. Select a project.

  3. Click the email address of the privilege-bearing service account, PRIV_SA.

  4. Click the Permissions tab.

  5. Under Principals with access to this service account, click Grant Access.

  6. Enter the email address of the caller Google Account, CALLER_ACCOUNT.

    For example, username@google.com.

  7. Select the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator).

  8. Click Save to grant the role to the user account.

gcloud

Grant the required role on PRIV_SA:

The gcloud iam service-accounts add-iam-policy-binding command grants a role on a service account.

Before using any of the command data below, make the following replacements:

  • PRIV_SA: The email address of the privilege-bearing service account for which the token is generated.
  • CALLER_ACCOUNT: The email address of the user account being used to request the short-lived token.

Execute the following command:

Linux, macOS, or Cloud Shell

gcloud iam service-accounts add-iam-policy-binding PRIV_SA --member=user:CALLER_ACCOUNT --role=roles/iam.serviceAccountTokenCreator

Windows (PowerShell)

gcloud iam service-accounts add-iam-policy-binding PRIV_SA --member=user:CALLER_ACCOUNT --role=roles/iam.serviceAccountTokenCreator

Windows (cmd.exe)

gcloud iam service-accounts add-iam-policy-binding PRIV_SA --member=user:CALLER_ACCOUNT --role=roles/iam.serviceAccountTokenCreator

You should receive a response similar to the following:

Updated IAM policy for serviceAccount [PRIV_SA].
bindings:
- members:
  - user:CALLER_ACCOUNT
  role: roles/iam.serviceAccountTokenCreator
etag: BwXhCB4eyjY=
version: 1

REST

First, read the allow policy for PRIV_SA:

The serviceAccounts.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 project ID. Project IDs are alphanumeric strings, like my-project.
  • PRIV_SA: The email address of the privilege-bearing service account for which the short-lived token is created.
  • POLICY_VERSION: The policy version to be returned. Requests should specify the most recent policy version, which is policy version 3. See Specifying a policy version when getting a policy for details.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/PRIV_SA:getIamPolicy

Request JSON body:

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

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

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

If you have not granted any roles on the service account, the response contains only an etag value. Include that etag value in the next step.

Next, modify the allow policy to grant CALLER_ACCOUNT the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator).

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

{
  "version": 1,
  "etag": "BwWKmjvelug=",
  "bindings": [
    {
      "role": "roles/serviceAccountAdmin",
      "members": [
        "user:admin@example.com"
      ]
    },
    {
      "role": "roles/iam.serviceAccountTokenCreator",
      "members": [
        "user:CALLER_ACCOUNT"
      ]
    }
  ]
}

Finally, write the updated allow policy:

The serviceAccounts.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 project ID. Project IDs are alphanumeric strings, like my-project.
  • PRIV_SA: The email address of the privilege-bearing service account for which the short-lived token is created.
  • POLICY_VERSION: The policy version to be returned. Requests should specify the most recent policy version, which is policy version 3. See Specifying a policy version when getting a policy for details.
  • POLICY: A JSON representation of the policy that you want to set. For more information about the format of a policy, see the Policy reference.

    For example, to set the allow policy shown in the previous step, replace POLICY with the following, where CALLER_ACCOUNT is the user account creating the short-lived token:

    {
      "version": 1,
      "etag": "BwWKmjvelug=",
      "bindings": [
        {
          "role": "roles/serviceAccountAdmin",
          "members": [
            "user:admin@example.com"
          ]
        },
        {
          "role": "roles/iam.serviceAccountTokenCreator",
          "members": [
            "user:CALLER_ACCOUNT"
          ]
        }
      ]
    }
    

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/PRIV_SA

Request JSON body:

{
  "policy": POLICY
}

To send your request, expand one of these options:

The response contains the updated allow policy.

Provide required permissions for a service account

When the calling application uses a service account as its identity, the following principals are involved:

  • Caller service account (CALLER_SA)

    This service account represents the calling application, which issues the request for the short-lived credentials.

  • Privilege-bearing service account (PRIV_SA)

    This service account is granted the IAM roles needed for the short-lived token. This is the service account for which the short-lived token is created.

To give CALLER_SA permissions to create short-lived credentials for PRIV_SA, you grant CALLER_SA the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator) on PRIV_SA.

Console

  1. In the Google Cloud console, go to the Service Accounts page.

    Go to Service Accounts

  2. Select a project.

  3. Click the email address of the privilege-bearing service account, PRIV_SA.

  4. Click the Permissions tab.

  5. Under Principals with access to this service account, click Grant Access.

  6. Enter the email address of the caller service account, CALLER_SA.

    For example, demo@my-project.iam.gserviceaccount.com.

  7. Select the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator).

  8. Click Save to grant the role to the service account.

gcloud

Grant the required role on PRIV_SA:

The gcloud iam service-accounts add-iam-policy-binding command grants a role on a service account.

Before using any of the command data below, make the following replacements:

  • PRIV_SA: The email address of the privilege-bearing service account for which the token is generated.
  • CALLER_SA: The email address of the service account representing the application that is requesting the short-lived token.

Execute the following command:

Linux, macOS, or Cloud Shell

gcloud iam service-accounts add-iam-policy-binding PRIV_SA --member=serviceAccount:CALLER_SA --role=roles/iam.serviceAccountTokenCreator

Windows (PowerShell)

gcloud iam service-accounts add-iam-policy-binding PRIV_SA --member=serviceAccount:CALLER_SA --role=roles/iam.serviceAccountTokenCreator

Windows (cmd.exe)

gcloud iam service-accounts add-iam-policy-binding PRIV_SA --member=serviceAccount:CALLER_SA --role=roles/iam.serviceAccountTokenCreator

You should receive a response similar to the following:

Updated IAM policy for serviceAccount [PRIV_SA].
bindings:
- members:
  - serviceAccount:CALLER_SA
  role: roles/iam.serviceAccountTokenCreator
etag: BwXhCB4eyjY=
version: 1

REST

First, read the allow policy for PRIV_SA:

The serviceAccounts.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 project ID. Project IDs are alphanumeric strings, like my-project.
  • PRIV_SA: The email address of the privilege-bearing service account for which the short-lived token is created.
  • POLICY_VERSION: The policy version to be returned. Requests should specify the most recent policy version, which is policy version 3. See Specifying a policy version when getting a policy for details.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/PRIV_SA:getIamPolicy

Request JSON body:

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

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

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

If you have not granted any roles on the service account, the response contains only an etag value. Include that etag value in the next step.

Next, modify the allow policy to grant CALLER_SA the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator).

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

{
  "version": 1,
  "etag": "BwWKmjvelug=",
  "bindings": [
    {
      "role": "roles/serviceAccountAdmin",
      "members": [
        "user:admin@example.com"
      ]
    },
    {
      "role": "roles/iam.serviceAccountTokenCreator",
      "members": [
        "serviceAccount:CALLER_SA"
      ]
    }
  ]
}

Finally, write the updated allow policy:

The serviceAccounts.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 project ID. Project IDs are alphanumeric strings, like my-project.
  • PRIV_SA: The email address of the privilege-bearing service account for which the short-lived token is created.
  • POLICY_VERSION: The policy version to be returned. Requests should specify the most recent policy version, which is policy version 3. See Specifying a policy version when getting a policy for details.
  • POLICY: A JSON representation of the policy that you want to set. For more information about the format of a policy, see the Policy reference.

    For example, to set the allow policy shown in the previous step, replace POLICY with the following, where CALLER_SA is the service account creating the short-lived token:

    {
      "version": 1,
      "etag": "BwWKmjvelug=",
      "bindings": [
        {
          "role": "roles/serviceAccountAdmin",
          "members": [
            "user:admin@example.com"
          ]
        },
        {
          "role": "roles/iam.serviceAccountTokenCreator",
          "members": [
            "serviceAccount:CALLER_SA"
          ]
        }
      ]
    }
    

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/PRIV_SA

Request JSON body:

{
  "policy": POLICY
}

To send your request, expand one of these options:

The response contains the updated allow policy.

Requesting short-lived credentials

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

The samples in this section require that you use a user account.

Generating an OAuth 2.0 access token

You can generate an OAuth 2.0 access token by using the gcloud CLI, the REST API, or the Cloud Client Libraries and Google API Client Libraries.

If you use the REST API, and your system is configured to allow extended token lifetimes, you can create a token with a lifetime longer than the default. The Google Cloud CLI does not support setting a lifetime for the token.

The samples below are designed to be used in a local development environment; the caller must be represented by a user account, rather than a service account.

To generate an OAuth 2.0 access token for the privilege-bearing service account:

gcloud

  1. Log in to the Google Cloud CLI as the caller Google Account.

    gcloud auth login CALLER_ACCOUNT
    
  2. Impersonate the privilege-bearing service account to generate the token.

    The gcloud auth print-access-token command generates an OAuth 2.0 access token for a service account.

    Before using any of the command data below, make the following replacements:

    • PRIV_SA: The email address of the privilege-bearing service account for which the short-lived token is created.
    • Execute the following command:

      Linux, macOS, or Cloud Shell

      gcloud auth print-access-token --impersonate-service-account=PRIV_SA
      

      Windows (PowerShell)

      gcloud auth print-access-token --impersonate-service-account=PRIV_SA
      

      Windows (cmd.exe)

      gcloud auth print-access-token --impersonate-service-account=PRIV_SA
      

      You should receive a response similar to the following:

      WARNING: This command is using service account impersonation. All API calls will be executed as
      [my-sa@my-project.iam.gserviceaccount.com].
      ya29.c.b0AXv0zTPnzTnDV8F8Aj5Fgy46Yf2v_v8eZIoKq7xGpfbpXuy23aQ1693m3gAuE8AZga7w6kdagN7a9bfdDYbdeoGY0CMHOClsCwIdutL7k_RFC672lOCbUgF5hS8Iu2nCA8hle-11LJXBLmaxFmH08ZTBJLuDrWSNd8cYqGYFunSC1K1qLIPBF18tsa0hxVgKPucI8b1A9L8_MK1JGLGcr0n7-zY77_lmbcdODG3NmIbLOGWOutjJgqSO_YoeCKK2QTUZIp5PG7RkKlXWnmYJA9pEahzNoQrs5sWZctc2bia9af_ITzqqlXC9h1Kj5-me6e8rd734MJvpagqYazRk0gGWpMb03XmMGpgPc_FBp4pnX9rGOzW83SNpcDz8zeFO1Q0Bo3N7CuZougjRce0y8I2_4rtw5ME_nV3wrCWa..................................................................................................................................................................................................................................................................................................
      

REST

The Service Account Credentials API's serviceAccounts.generateAccessToken method generates an OAuth 2.0 access 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.
  • 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 the constraints/iam.allowServiceAccountCredentialLifetimeExtension list constraint.

HTTP method and URL:

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

Request JSON body:

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

To send your request, expand one of these options:

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

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

Generating OpenID Connect ID tokens

You can generate an OpenID Connect (OIDC) ID token by using the gcloud CLI, the REST API, or the Cloud Client Libraries and Google API Client Libraries.

The samples below are designed to be used in a local development environment; the caller must be represented by a user account, rather than a service account.

OIDC ID tokens are valid for 1 hour (3,600 seconds).

To generate a Google-signed OIDC ID token for the privilege-bearing service account:

gcloud

  1. Log in to the Google Cloud CLI as the caller Google Account.

    gcloud auth login CALLER_ACCOUNT
    
  2. Impersonate the privilege-bearing service account to generate the token.

    The gcloud auth print-identity-token command generates an OIDC ID token for a service account.

    Before using any of the command data below, 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.
      • Execute the following command:

        Linux, macOS, or Cloud Shell

        gcloud auth print-identity-token --impersonate-service-account=PRIV_SA --audiences="AUDIENCE_NAME"
        

        Windows (PowerShell)

        gcloud auth print-identity-token --impersonate-service-account=PRIV_SA --audiences="AUDIENCE_NAME"
        

        Windows (cmd.exe)

        gcloud auth print-identity-token --impersonate-service-account=PRIV_SA --audiences="AUDIENCE_NAME"
        

        You should receive a response similar to the following:

        WARNING: This command is using service account impersonation. All API calls will be executed as
        [my-sa@my-project.iam.gserviceaccount.com].
        eyJhbGciOiJSUzI1NiIsImtpZDNhMDg4ZDRmZmMjJkYTVmZTM5MDZjY2MiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOiJ3d3cuZXhhbXBsJhenAiOiIxMTYzwNDYyMDk0ODIiLCJleHAiOjE2NTQ4ODU0MzEsImlhdCI6MTY1NDg4MTgzMSwiaXN6Ly9hY2NvdW50cy5nb29nbGUuY29tIiwic3ViIMDQ2MjA5NDgyIn0.F7mu8IHj5VQdu7ItFrnYAKyGd7YqXuOP_rFLc98q8BaFBycAF1zAQnSnwqnSUXba0UK9PDT_-IOry68qLwBObz4XlX9lk0ehpN0O0W9FcFToKLB6wefXXPd4h7xtuPe5KzmpSOqj2Qqv34HriGw00Nqd-oGSgNY_lZ4wGEf4rT4oQa_kEcrY57Q2G6pwd769BhgeFwoLi5aK_Cv2kvf_zfMszC-xlkP9zwWQ8XinJBwe-qcQBa4NTgrbueNtXsEjccBS366zmw
        

REST

The Service Account Credentials API's serviceAccounts.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:

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

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

Creating a self-signed JSON Web Token (JWT)

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

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

To run the sample below, you must use a user account as the caller credentials.

To generate a self-signed JWT for the privilege-bearing service account:

REST

The Service Account Credentials API's serviceAccounts.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:

  • PRIV_SA: The email address of the privilege-bearing service account for which the short-lived token is created.
  • 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.

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

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

    { \"iss\": \"PRIV_SA", \"sub\": \"PRIV_SA\", \"aud\": \"https://firestore.googleapis.com/\", \"iat\": 1529350000, \"exp\": EXP }

HTTP method and URL:

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

Request JSON body:

{
  "payload": "JWT_PAYLOAD"
}

To send your request, expand one of these options:

If the signJwt 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 the signedJwt 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"
}

Creating a self-signed blob

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

To run the sample below, you must use a user account as the caller credentials.

To generate a self-signed blob for the privilege-bearing service account:

REST

The Service Account Credentials API's serviceAccounts.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:

  • PRIV_SA: The email address of the privilege-bearing service account for which the short-lived token is created.
  • BLOB_PAYLOAD: A base64-encoded string of bytes. For example, VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu.

HTTP method and URL:

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

Request JSON body:

{
  "payload": "BLOB_PAYLOAD"
}

To send your request, expand one of these options:

If the signBlob 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 the signedBlob 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 the keyId field in the response.

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