Obtaining short-lived credentials with identity federation

This guide describes how you can use a workload identity pool and provider to obtain short-lived credentials by following this process:

  1. Obtain a credential from the trusted identity provider.
  2. Exchange the credential for a token from the Security Token Service.
  3. Use the token from the Security Token Service to impersonate a service account and obtain a short-lived Google access token.

Using the short-lived Google access tokens, you can then access any Google Cloud resources that the service account has been granted access to.

Before you begin

  1. Enable the IAM, Security Token Service, and Service Account Credentials APIs.

    Enable the APIs

  2. Federate with an external identity provider by creating a workload identity federation pool and provider

  3. Create a service account that you want external identities to impersonate.

  4. Grant the service account access to resources that you want external identities to access.

Granting external identities permission to impersonate a service account

To allow external identities to impersonate a service account, you have to grant them the Workload Identity User role (roles/iam.workloadIdentityUser) on the service account. You can grant the role to a specific external identity, or to multiple external identities:

  • For a specific external identity, write an attribute condition that checks the google.subject attribute.
  • For a group of external identities, write an attribute condition that checks the google.groups attribute or a custom attribute attribute.NAME.
  • For all external identities in the workload identity pool, you do not use an attribute condition.

Console

  1. In the Cloud Console, go to the Workload Identity Pools page.

    Go to Workload Identity Pools

  2. Find the workload identity pool that contains the Azure identities and click Edit.

  3. Click Grant access.

  4. In the Service account drop-down list, select the service account that the external identities will impersonate.

  5. Choose which identities in the pool can impersonate the service account:

    • To allow only specific identities of the workload identity pool to impersonate the service account, select Only identities matching the filter.

      In the Attribute name drop-down list, select the attribute that you want to filter on.

      In the Attribute value field, enter the expected value of the attribute.

      For example, if you use an attribute mapping google.subject=assertion.sub, set Attribute name to subject and Attribute value to the value of the sub claim in tokens issued by your external identity provider.

    • To allow all external identities of the workload identity pool to impersonate the service account, select All identities in the pool.

  6. Click Save.

  7. Click Dismiss.

gcloud

  1. Create an identifier for the external identities:

    • A specific external identity:

      principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT
      
    • A group of external identities:

      principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/group/GROUP
      
    • All external identities that have a certain attribute:

      principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE
      
    • All external identities in a workload identity pool:

      principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/*
      

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: Pool ID of the workload identity pool
    • SUBJECT: Expected value for the attribute that you've mapped to google.subject
    • GROUP: Expected value for the attribute that you've mapped to google.groups
    • ATTRIBUTE_NAME: Name of a custom attribute in your attribute mapping

    To obtain the project number of your current project, you can use the following command:

    gcloud projects describe $(gcloud config get-value core/project) --format=value\(projectNumber\)
    
  2. Grant the Workload Identity User role (roles/iam.workloadIdentityUser) to the service account:

    gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_EMAIL \
        --role=roles/iam.workloadIdentityUser \
        --member="MEMBER_EXPRESSION"
    

    Replace the following values:

    • SERVICE_ACCOUNT_EMAIL: Email address of the service account
    • MEMBER_ID: Member identifier that you identified in the previous step

Authenticating by using client libraries, the gcloud tool, or Terraform

The Cloud Client Libraries, the gcloud tool, and Terraform, can automatically obtain external credentials, and use these credentials to impersonate a service account. To let libraries and tools complete this process, you have to provide a credential configuration file. This file defines the following:

  • Where to obtain external credentials from
  • Which workload identity pool and provider to use
  • Which service account to impersonate

The way credential configuration files are used by the client libraries depends on your external identity provider:

AWS

The client libraries automatically obtain temporary credentials from the EC2 instance metadata.

Azure

The client libraries automatically obtain access tokens from the Azure Instance Metadata Service (IMDS).

GitHub Actions

Because the parameters required to obtain a GitHub ID token vary for each workflow execution, you can't use a static credential configuration file in a GitHub Actions workflow.

Use the google-github-actions/auth action to automatically generate a credential configuration file during workflow execution. Client libraries and tools such as terraform can then use this credential configuration file to automatically obtain Google credentials.

OIDC

The client libraries obtain credentials from a local file, or an HTTP URL:

  • File-sourced credentials: Tokens are loaded from a file. Another process must refresh this file with a new OIDC token before the old token expires. For example, if the token has a lifetime of 1 hour, you must refresh the file before it is 1 hour old.
  • URL-sourced credentials: Tokens are loaded from a local server with an endpoint that responds to HTTP GET requests. The response must be an OIDC ID token, either in plain text or in JSON format.

SAML

The client libraries obtain credentials from a local file, or an HTTP URL:

  • File-sourced credentials: Assertions are loaded from a file. Another process must refresh this file with a new base64url-encoded SAML assertion before the old assertion expires. For example, if the assertion has a lifetime of 1 hour, you must refresh the file before it is 1 hour old.
  • URL-sourced credentials: Assertions are loaded from a local server with an endpoint that responds to HTTP GET requests. The response must be either a base64url-encoded SAML assertion or JSON containing a base64url-encoded SAML assertion.

Follow these steps to let client libraries or Terraform use workload identity federation to authenticate:

  1. Create a credential configuration file:

    Console

    Download a credential configuration file in the Cloud Console:

    1. In the Cloud Console, go to the Workload Identity Pools page.

      Go to Workload Identity Pools

    2. Find the workload identity pool that contains the identity provider you want to use and click Edit.

    3. Select Connected service accounts.

    4. Find the service account you want to use and click Download.

    5. In the Configure your application dialog, select the provider that contains the external identities that will impersonate the service account.

    6. Provide the following additional settings:

      AWS

      No additional settings required.

      Azure

      Resource path: Application ID URI of the Azure application

      OIDC

      OIDC token path: Local file path or URL to obtain credentials from.

      Format type: Format of the file or URL response where the ID token is retrieved from.

      Subject token field name: Field in the response that contains the token (if format type is json).

      SAML

      SAML assertion path: Local file path or URL to obtain credentials from.

      Format type: Format of the file or URL response where the assertion is retrieved from.

      Assertion field name: Field in the response that contains the assertion (if format type is json).

    7. Select Download config to download the credential configuration file, then click Dismiss.

    gcloud

    Create a credential configuration file by using gcloud iam workload-identity-pools create-cred-config:

    AWS

    Create a credential configuration file that lets the library obtain an access token from EC2 instance metadata:

    gcloud iam workload-identity-pools create-cred-config \
        projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
        --service-account=SERVICE_ACCOUNT_EMAIL \
        --aws \
        --output-file=FILEPATH.json
    

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
    • SERVICE_ACCOUNT_EMAIL: Email address of the service account
    • FILEPATH: File to save configuration to

    Azure

    Create a credential configuration file that lets the library obtain an access token from the Azure Instance Metadata Service (IMDS):

    gcloud iam workload-identity-pools create-cred-config \
        projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
        --service-account=SERVICE_ACCOUNT_EMAIL \
        --azure \
        --app-id-uri APPLICATION_ID_URI \
        --output-file=FILEPATH.json
    

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
    • SERVICE_ACCOUNT_EMAIL: Email address of the service account
    • APPLICATION_ID_URI: Application ID URI of the Azure application
    • FILEPATH: File to save configuration to

    OIDC

    To use file-sourced credentials, use the --credential-source-file flag:

    gcloud iam workload-identity-pools create-cred-config \
        projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
        --service-account=SERVICE_ACCOUNT_EMAIL \
        --output-file=FILEPATH.json \
        --credential-source-file=TOKEN_FILEPATH \
        --credential-source-type=SOURCE_TYPE \
        --credential-source-field-name=FIELD_NAME
    

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
    • SERVICE_ACCOUNT_EMAIL: Email address of the service account
    • FILEPATH: File to save configuration to
    • TOKEN_FILEPATH: Path where OIDC ID tokens are stored
    • SOURCE_TYPE: Format of the OIDC ID token file, set to text (default) or json
    • FIELD_NAME: Field in the text file that contains the token (if SOURCE_TYPE is json)

    To use URL-sourced credentials,use the --credential-source-url flag:

    gcloud iam workload-identity-pools create-cred-config \
        projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
        --service-account=SERVICE_ACCOUNT_EMAIL \
        --output-file=FILEPATH.json \
        --credential-source-url="TOKEN_URL" \
        --credential-source-headers="KEY_1=VALUE_1,KEY_2=VALUE_2" \
        --credential-source-type=source_type \
        --credential-source-field-name=field_name
    

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
    • SERVICE_ACCOUNT_EMAIL: Email address of the service account
    • FILEPATH: File to save configuration to
    • TOKEN_URL: URL to retrieve OIDC ID token from
    • KEY_n, VALUE_n: Custom headers to include in HTTP request to TOKEN_URL
    • SOURCE_TYPE: Format of the OIDC ID token file, set to text (default) or json
    • FIELD_NAME: Field in the text file that contains the token (if SOURCE_TYPE is json)

    SAML

    To use file-sourced credentials, use the --credential-source-file flag:

    gcloud iam workload-identity-pools create-cred-config \
        projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
        --service-account=SERVICE_ACCOUNT_EMAIL \
        --output-file=FILEPATH.json \
        --credential-source-file=TOKEN_FILEPATH \
        --credential-source-type=SOURCE_TYPE \
        --credential-source-field-name=FIELD_NAME \
        --subject-token-type=urn:ietf:params:oauth:token-type:saml2
    

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
    • SERVICE_ACCOUNT_EMAIL: Email address of the service account
    • FILEPATH: File to save configuration to
    • TOKEN_FILEPATH: Path where SAML assertions are stored
    • SOURCE_TYPE: Format of the SAML assertion file, set to text (default) or json
    • FIELD_NAME: Field in the text file that contains the assertion (if SOURCE_TYPE is json)

    To use URL-sourced credentials,use the --credential-source-url flag:

    gcloud iam workload-identity-pools create-cred-config \
        projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \
        --service-account=SERVICE_ACCOUNT_EMAIL \
        --output-file=FILEPATH.json \
        --credential-source-url="TOKEN_URL" \
        --credential-source-headers="KEY_1=VALUE_1,KEY_2=VALUE_2" \
        --credential-source-type=source_type \
        --credential-source-field-name=field_name
        --subject-token-type=urn:ietf:params:oauth:token-type:saml2
    

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
    • SERVICE_ACCOUNT_EMAIL: Email address of the service account
    • FILEPATH: File to save configuration to
    • TOKEN_URL: URL to retrieve SAML assertion from
    • KEY_n, VALUE_n: Custom headers to include in HTTP request to TOKEN_URL
    • SOURCE_TYPE: Format of the SAML assertion file, set to text (default) or json
    • FIELD_NAME: Field in the text file that contains the assertion (if SOURCE_TYPE is json)

    GitHub Actions

    Edit your GitHub Actions YAML file and add the following:

    • Allow the job to fetch a GitHub ID token by adding the following configuration:

      permissions:
        id-token: write
        contents: read
      
    • Add a step to create a credentials configuration file:

      - id: 'auth'
        name: 'Authenticate to Google Cloud'
        uses: 'google-github-actions/auth@v0.3.1'
        with:
          create_credentials_file: true
          workload_identity_provider: 'projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID'
          service_account: 'SERVICE_ACCOUNT_EMAIL'
      

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
    • SERVICE_ACCOUNT_EMAIL: Email address of the service account

    Example:

    jobs:
      build:
        # Allow the job to fetch a GitHub ID token
        permissions:
          id-token: write
          contents: read
    
        runs-on: ubuntu-latest
    
        steps:
          - uses: actions/checkout@v2
    
          - id: 'auth'
            name: 'Authenticate to Google Cloud'
            uses: 'google-github-actions/auth@v0.3.1'
            with:
              create_credentials_file: true
              workload_identity_provider: 'projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID'
              service_account: 'SERVICE_ACCOUNT_EMAIL'
    
  2. Initialize an environment variable GOOGLE_APPLICATION_CREDENTIALS and point it to the credential configuration file:

    Bash

      export GOOGLE_APPLICATION_CREDENTIALS=`pwd`/FILEPATH.json
      
    where FILEPATH is the relative file path to the credential configuration file.

    PowerShell

      $env:GOOGLE_APPLICATION_CREDENTIALS = Resolve-Path 'FILEPATH.json'
      
    where FILEPATH is the relative file path to the credential configuration file.

    GitHub Actions YAML

    The google-github-actions/auth action automatically initializes GOOGLE_APPLICATION_CREDENTIALS.
  3. Use a client library that supports workload identity federation and can find credentials automatically:

    C++

    Most of the Google Cloud Client Libraries for C++ support identity federation by using a ChannelCredentials object, which is created by calling grpc::GoogleDefaultCredentials(). To initialize this credential, you must build the client libraries with version 1.36.0 or later of gRPC.

    The Cloud Storage Client Library for C++ uses the REST API, not gRPC, so it does not support identity federation.

    Go

    Client libraries for Go support identity federation if they use version v0.0.0-20210218202405-ba52d332ba99 or later of the golang.org/x/oauth2 module.

    To check which version of this module your client library uses, run the following commands:

    cd $GOPATH/src/cloud.google.com/go
    go list -m golang.org/x/oauth2
    

    Java

    Client libraries for Java support identity federation if they use version 0.24.0 or later of the com.google.auth:google-auth-library-oauth2-http artifact.

    To check which version of this artifact your client library uses, run the following Maven command in your application directory:

    mvn dependency:list -DincludeArtifactIds=google-auth-library-oauth2-http
    

    Node.js

    Client libraries for Node.js support identity federation if they use version 7.0.2 or later of the google-auth-library package.

    To check which version of this package your client library uses, run the following command in your application directory:

    npm list google-auth-library
    

    When you create a GoogleAuth object, you can specify a project ID, or you can allow GoogleAuth to find the project ID automatically. To find the project ID automatically, the service account in the configuration file must have the Browser role (roles/browser), or a role with equivalent permissions, on your project. For details, see the README for the google-auth-library package.

    Python

    Client libraries for Python support identity federation if they use version 1.27.0 or later of the google-auth package.

    To check which version of this package your client library uses, run the following command in the environment where the package is installed:

    pip show google-auth
    

    To specify a project ID for the authentication client, you can set the GOOGLE_CLOUD_PROJECT environment variable, or you can allow the client to find the project ID automatically. To find the project ID automatically, the service account in the configuration file must have the Browser role (roles/browser), or a role with equivalent permissions, on your project. For details, see the user guide for the google-auth package.

    gcloud

    To authenticate using workload identity federation, use the gcloud auth login command:

    gcloud auth login --cred-file=FILEPATH.json
    

    where FILEPATH is the file path to the credential configuration file.

    Support for workload identity federation is available in version 363.0.0 and later versions of the Cloud SDK.

    Terraform

    The Google Cloud provider supports workload identity federation if you use version 3.61.0 or later:

    terraform {
      required_providers {
        google = {
          source  = "hashicorp/google"
          version = "~> 3.61.0"
        }
      }
    }
    

Authenticating by using the REST API

If you can't use the client libraries, you can follow these steps to let an external identity obtain a short-lived access token by using the REST API:

  1. Obtain credentials from your external identity provider:

    AWS

    Create a JSON document that contains the information that you would normally include in a request to the AWS GetCallerIdentity() endpoint, including a valid request signature.

    Workload identity federation refers to this JSON document as a GetCallerIdentity token. The token lets workload identity federation verify the identity without revealing the AWS secret access key.

    A GetCallerIdentity token looks similar to the following:

    {
      "url": "https://sts.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15",
      "method": "POST",
      "headers": [
        {
          "key": "Authorization",
          "value" : "AWS4-HMAC-SHA256 Credential=AKIASOZTBDV4D7ABCDEDF/20200228/us-east-1/sts/aws4_request, SignedHeaders=host;x-amz-date,Signature=abcedefdfedfd"
        },
        {
          "key": "host",
          "value": "sts.amazonaws.com"
        },
        {
          "key": "x-amz-date",
          "value": "20200228T225005Z"
        },
        {
          "key": "x-goog-cloud-target-resource",
          "value": "//iam.googleapis.com/projects/12345678/locations/global/workloadIdentityPools/my-pool/providers/my-aws-provider"
        },
        {
          "key": "x-amz-security-token",
          "value": "GizFWJTqYX...xJ55YoJ8E9HNU="
        }
      ]
    }
    

    The token contains the following fields:

    • url: The URL of the AWS STS endpoint for GetCallerIdentity(), with the body of a standard GetCallerIdentity() request appended as query parameters. For example, https://sts.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15. Regional endpoints are also supported.
    • method: The HTTP request method: POST.
    • headers: The HTTP request headers, which must include:
      • Authorization: The request signature.
      • host: The hostname of the url field; for example, sts.amazonaws.com.
      • x-amz-date: The time you will send the request, formatted as an ISO 8601 Basic string. This value is typically set to the current time and is used to help prevent replay attacks.
      • x-goog-cloud-target-resource: The full resource name of the identity provider without a https: prefix. For example:
        //iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID
        
      • x-amz-security-token: Session token. Only required if you are using temporary security credentials.

    The following example creates a GetCallerIdentity token:

    import json
    import urllib
    
    import boto3
    from botocore.auth import SigV4Auth
    from botocore.awsrequest import AWSRequest
    
    
    def create_token_aws(project_id: str, pool_id: str, provider_id: str) -> None:
        # Prepare a GetCallerIdentity request.
        request = AWSRequest(
            method="POST",
            url="https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15",
            headers={
                "Host": "sts.amazonaws.com",
                "x-goog-cloud-target-resource": f"//iam.googleapis.com/projects/{project_id}/locations/global/workloadIdentityPools/{pool_id}/providers/{provider_id}"
            })
    
        # Set the session credentials and Sign the request.
        # get_credentials loads the required credentials as environment variables.
        # Refer:
        # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
        SigV4Auth(boto3.Session().get_credentials(), "sts", "us-east-1").add_auth(request)
    
        # Create token from signed request.
        token = {
            "url": request.url,
            "method": request.method,
            "headers": []
        }
        for key, value in request.headers.items():
            token["headers"].append({"key": key, "value": value})
    
        # The token lets workload identity federation verify the identity without revealing the AWS secret access key.
        print("Token:\n%s" % json.dumps(token, indent=2, sort_keys=True))
        print("URL encoded token:\n%s" % urllib.parse.quote(json.dumps(token)))
    
    
    def main():
        # TODO(Developer): Replace the below credentials.
        project_id = "my-project-id"
        pool_id = "my-pool-id"
        provider_id = "my-provider-id"
    
        create_token_aws(project_id, pool_id, provider_id)
    
    
    if __name__ == "__main__":
        main()

    Initialize the following variables:

    Bash

    SUBJECT_TOKEN_TYPE="urn:ietf:params:aws:token-type:aws4_request"
    SUBJECT_TOKEN=TOKEN
    

    PowerShell

    $SubjectTokenType = "urn:ietf:params:aws:token-type:aws4_request"
    $SubjectToken = "TOKEN"
    

    Where TOKEN is the URL encoded GetCallerIdentity token.

    Azure

    Connect to an Azure VM that has an assigned managed identity and obtain an access token from the Azure Instance Metadata Service (IMDS):

    Bash

    SUBJECT_TOKEN_TYPE="urn:ietf:params:oauth:token-type:jwt"
    SUBJECT_TOKEN=$(curl \
      "http://169.254.169.254/metadata/identity/oauth2/token?resource=APP_ID_URI&api-version=2018-02-01" \
      -H "Metadata: true" | jq -r .access_token)
    echo $SUBJECT_TOKEN
    

    This command uses the jq tool. jq is available by default in Cloud Shell.

    PowerShell

    $SubjectTokenType = "urn:ietf:params:oauth:token-type:jwt"
    $SubjectToken = (Invoke-RestMethod `
      -Uri "http://169.254.169.254/metadata/identity/oauth2/token?resource=APP_ID_URI&api-version=2018-02-01" `
      -Headers @{Metadata="true"}).access_token
    Write-Host $SubjectToken
    

    Where APP_ID_URI is the Application ID URI of the application that you've configured for workload identity federation.

    GitHub Actions

    Use the google-github-actions/auth to obtain a GitHub ID token and to exchange it against a short-lived access token:

    • Allow the job to fetch a GitHub ID token by adding the following configuration:

      permissions:
        id-token: write
        contents: read
      
    • Add a step to generate an access token and make it available in a variable ${{ steps.auth.outputs.access_token }}:

      - id: 'auth'
        name: 'Authenticate to Google Cloud'
        uses: 'google-github-actions/auth@v0.3.1'
        with:
          token_format: 'access_token'
          workload_identity_provider: 'projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID'
          service_account: 'SERVICE_ACCOUNT_EMAIL'
      

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
    • SERVICE_ACCOUNT_EMAIL: Email address of the service account

    Example:

    jobs:
      build:
        # Allow the job to fetch a GitHub ID token
        permissions:
          id-token: write
          contents: read
    
        runs-on: ubuntu-latest
    
        steps:
          - uses: actions/checkout@v2
    
          - id: 'auth'
            name: 'Authenticate to Google Cloud'
            uses: 'google-github-actions/auth@v0.3.1'
            with:
              token_format: 'access_token'
              workload_identity_provider: 'projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID'
              service_account: 'SERVICE_ACCOUNT_EMAIL'
    

    Skip the following steps.

    OIDC

    Obtain a token from your external identity provider and initialize the following variables:

    Bash

    SUBJECT_TOKEN_TYPE="urn:ietf:params:oauth:token-type:jwt"
    SUBJECT_TOKEN=TOKEN
    

    PowerShell

    $SubjectTokenType = "urn:ietf:params:oauth:token-type:jwt"
    $SubjectToken = "TOKEN"
    

    Where TOKEN is the token issued by your external identity provider.

    SAML

    Obtain an assertion from your external identity provider and initialize a variable:

    Bash

    SUBJECT_TOKEN_TYPE="urn:ietf:params:oauth:token-type:saml2"
    SUBJECT_TOKEN=ASSERTION
    

    PowerShell

    $SubjectTokenType = "urn:ietf:params:oauth:token-type:saml2"
    $SubjectToken = "ASSERTION"
    

    Where ASSERTION is the base64url-encoded assertion issued by your external identity provider.

  2. Use the Security Token Service API to exchange the credential against a short-lived access token:

    Bash

    STS_TOKEN=$(curl -0 -X POST https://sts.googleapis.com/v1/token \
        -H 'Content-Type: text/json; charset=utf-8' \
        -d @- <<EOF | jq -r .access_token
        {
            "audience"           : "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID",
            "grantType"          : "urn:ietf:params:oauth:grant-type:token-exchange",
            "requestedTokenType" : "urn:ietf:params:oauth:token-type:access_token",
            "scope"              : "https://www.googleapis.com/auth/cloud-platform",
            "subjectTokenType"   : "$SUBJECT_TOKEN_TYPE",
            "subjectToken"       : "$SUBJECT_TOKEN"
        }
    EOF)
    echo $STS_TOKEN
    

    PowerShell

    $StsToken = (Invoke-RestMethod `
        -Method POST `
        -Uri "https://sts.googleapis.com/v1/token" `
        -ContentType "application/json" `
        -Body (@{
            "audience"           = "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID"
            "grantType"          = "urn:ietf:params:oauth:grant-type:token-exchange"
            "requestedTokenType" = "urn:ietf:params:oauth:token-type:access_token"
            "scope"              = "https://www.googleapis.com/auth/cloud-platform"
            "subjectTokenType"   = $SubjectTokenType
            "subjectToken"       = $SubjectToken
        } | ConvertTo-Json)).access_token
    Write-Host $StsToken
    

    Replace the following values:

    • PROJECT_NUMBER: Project number of the project that contains the workload identity pool
    • POOL_ID: ID of the workload identity pool
    • PROVIDER_ID: ID of the workload identity pool provider
  3. Use the token from the Security Token Service to invoke the generateAccessToken method of the IAM Service Account Credentials API to obtain an access token:

    Bash

    ACCESS_TOKEN=$(curl -0 -X POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL:generateAccessToken \
        -H "Content-Type: text/json; charset=utf-8" \
        -H "Authorization: Bearer $STS_TOKEN" \
        -d @- <<EOF | jq -r .accessToken
        {
            "scope": [ "https://www.googleapis.com/auth/cloud-platform" ]
        }
    EOF)
    echo $ACCESS_TOKEN
    

    PowerShell

    $AccessToken = (Invoke-RestMethod `
        -Method POST `
        -Uri "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE_ACCOUNT_EMAIL:generateAccessToken" `
        -Headers @{ "Authorization" = "Bearer $StsToken" } `
        -ContentType "application/json" `
        -Body (@{
            "scope" = , "https://www.googleapis.com/auth/cloud-platform"
        } | ConvertTo-Json)).accessToken
    Write-Host $AccessToken
    

    Replace SERVICE_ACCOUNT_EMAIL with the email address of the service account.

What's next