Obtain short-lived tokens for Workforce Identity Federation

This guide shows you how to use a workforce identity pool and workforce identity pool provider to obtain short-lived tokens from Security Token Service. You can use the tokens to access Google Cloud resources that support Workforce Identity Federation and to which you have been granted access.

You obtain short-lived tokens 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.

Before you begin

  1. Configure Workforce Identity Federation or, for IdP-specific instructions, see the following guides:

  2. You must know your workforce pool ID or provider ID.

  3. Ensure that you have the Identity and Access Management (IAM) permission serviceusage.services.use. The least-privileged role that contains this permission is Service Usage Consumer (roles/serviceusage.serviceUsageConsumer).

  4. Enable the IAM and Security Token Service APIs.

    Enable the APIs

  5. Install the Google Cloud CLI, then initialize it by running the following command:

    gcloud init

Exchange external credentials for a Google Cloud access token

This section shows you how to use Security Token Service to exchange your external credentials for an access token that grants access to Google Cloud. You do this using the gcloud CLI, REST API, and Cloud Client Libraries, as described later in this guide.

If you need long-lived access, you can configure a long-running process to continuously refresh credentials on that machine. Alternatively, you can run a local server in the background with an endpoint that returns the credentials.

Browser-based sign-in with the gcloud CLI

This section describes how to configure gcloud CLI to use a browser-based sign-in flow. To do so, you create a sign-in configuration file and then either reference the file in calls to gcloud auth login or activate it so that it is used by default.

Create the login configuration file

To create the login configuration file, run the following command. You can optionally activate the file as the default for the gcloud CLI by using the --activate flag.

gcloud iam workforce-pools create-login-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --output-file=LOGIN_CONFIG_FILE

Replace the following:

  • WORKFORCE_POOL_ID: the workforce identity pool ID
  • PROVIDER_ID: the workforce identity pool provider ID
  • LOGIN_CONFIG_FILE: a path to the login configuration file that you specify—for example, login.json

The file contains contains the endpoints used by the gcloud CLI to enable the browser-based authentication flow and set the audience to the IdP that was configured in the workforce identity pool provider. The file doesn't contain confidential information.

The output looks similar to the following:

{
  "type": "external_account_authorized_user_login_config",
  "audience": "//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID",
  "auth_url": "https://auth.cloud.google/authorize",
  "token_url": "https://sts.googleapis.com/v1/oauthtoken",
  "token_info_url": "https://sts.googleapis.com/v1/introspect",
}

Sign in using browser-based authentication

To authenticate using browser-based sign-in authentication, you can use one of the following methods:

  • If you used the --activate flag when you created the configuration file, or if you activated the configuration file with gcloud config set auth/LOGIN_CONFIG_FILE, the gcloud CLI uses your configuration file automatically:

    gcloud auth login
    
  • To sign in by specifying the location of the configuration file, run the following command:

    gcloud auth login --login-config=LOGIN_CONFIG_FILE
    
  • To use an environment variable to specify the location of the configuration file, set CLOUDSDK_AUTH_LOGIN_CONFIG_FILE to the configuration path.

Disable browser-based sign-in

To discontinue using the login configuration file, do the following:

  • If you used the --activate flag when you created the configuration file, or if you activated the configuration file with gcloud config set auth/LOGIN_CONFIG_FILE, you must run the following command to unset it:

    gcloud config unset auth/login_config_file
    
  • Clear the CLOUDSDK_AUTH_LOGIN_CONFIG_FILE environment variable, if it is set.

Use configuration files for sign-in

As an alternative to browser-based sign-in, this section shows you different ways to use credential configuration files to provide access to authenticated Google Cloud actions. Setting up the configuration files does not require you to be logged in to the gcloud CLI.

How you set up your configuration file depends on whether your IdP uses OIDC or SAML.

OIDC

You can source the credentials that you use to set up your configuration file from the following sources:

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 one hour, you must refresh the file before it is one hour old.

To generate the configuration file with a file-sourced credential, execute the following command:

gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:id_token \
    --credential-source-file=PATH_TO_OIDC_ID_TOKEN \
    --workforce-pool-user-project=WORKFORCE_POOL_USER_PROJECT \
    --output-file=config.json

Replace the following:

  • WORKFORCE_POOL_ID: the workforce pool ID
  • PROVIDER_ID: the provider ID
  • PATH_TO_OIDC_TOKEN: the path to the OIDC IdP credential file
  • WORKFORCE_POOL_USER_PROJECT: the project number or ID associated with the workforce pools user project.

The principal must have serviceusage.services.use permission on this project.

Running the command produces an OIDC IdP config file similar to the following:

{
  "type": "external_account",
  "audience": "//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID",
  "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
  "token_url": "https://sts.googleapis.com/v1/token",
  "workforce_pool_user_project": "WORKFORCE_POOL_USER_PROJECT",
  "credential_source": {
    "file": "PATH_TO_OIDC_CREDENTIALS_FILE"
  }
}

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.

To generate the configuration file with a URL-sourced credential, execute the following command:

gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:id_token \
    --credential-source-url=URL_TO_RETURN_OIDC_ID_TOKEN \
    --workforce-pool-user-project=WORKFORCE_POOL_USER_PROJECT \
    --output-file=config.json

Replace the following:

  • WORKFORCE_POOL_ID: the workforce pool ID.
  • PROVIDER_ID: the provider ID.
  • URL_TO_RETURN_OIDC_ID_TOKEN: the URL to call to retrieve the OIDC credentials, such as an OIDC ID token—for example: http://localhost:5000/token.
  • WORKFORCE_POOL_USER_PROJECT: the project number used for quota and billing. The principal needs to have serviceusage.services.use permission on this project.

Running the command produces an OIDC IdP config file similar to the following:

{
  "type": "external_account",
  "audience": "//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID",
  "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
  "token_url": "https://sts.googleapis.com/v1/token",
  "workforce_pool_user_project": "WORKFORCE_POOL_USER_PROJECT",
  "credential_source": {
    "url": "URL_TO_RETURN_OIDC_ID_TOKEN"
  }
}

Non-interactive executable-sourced credentials

Tokens are loaded from a local executable. The executable must provide a valid, unexpired OIDC ID token in JSON format to stdout:

{
  "version": 1,
  "success": true,
  "token_type": "urn:ietf:params:oauth:token-type:id_token",
  "id_token": "HEADER.PAYLOAD.SIGNATURE",
  "expiration_time": 1620499962
}

These fields are required for a successful response, with the exception of expiration_time. The expiration_time field is only required when an output file has been specified in the credential configuration.

The executable must surface any errors to stdout in the following JSON format:

{
  "version": 1,
  "success": false,
  "code": "401",
  "message": "Caller not authorized."
}

These fields are all required for an error response. The code and message fields are used by the client libraries when raising the appropriate error.

The command can return the following fields:

  • version: the version of the JSON output. Only version 1 is supported.
  • success: the status of the response. When the status is true, the executable must exit with exit code 0 and the response must contain the following fields:

    • token_type: id_token
    • expiration_time field, if an output file is specified in the credential configuration

    When the status is false, the executable must exit with a non-zero value and the response must contain the following fields:

    • code
    • message
  • token_type: the third-party subject token type, which must be urn:ietf:params:oauth:token-type:id_token

  • id_token: the third-party OIDC token

  • expiration_time: the third-party OIDC token expiration time in seconds (Unix epoch time)

  • code: the error code string

  • message: the error message

The client libraries populate the following environment variables when the executable is run:

  • GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE: the audience field from the credential configuration. Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE: the expected subject token type. Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE: the output file location from the credential configuration. Only present when specified in the credential configuration.

These environment variables can be used by the executable to avoid hardcoding these values.

To enable this credential sourcing method with the client libraries, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable must be set to 1.

To generate the configuration file with a executable-sourced credential, execute the following command:

gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:id_token  \
    --executable-command=EXECUTABLE_COMMAND \
    --executable-timeout-millis=EXECUTABLE_TIMEOUT \
    --executable-output-file=EXECUTABLE_OUTPUT_FILE \
    --workforce-pool-user-project=WORKFORCE_POOL_USER_PROJECT \
    --output-file /path/to/generated/config.json

Replace the following:

  • WORKFORCE_POOL_ID: the workforce pool ID.
  • PROVIDER_ID: the provider ID.
  • EXECUTABLE_COMMAND: the full command, including arguments, to run to retrieve the subject token, such as an OIDC ID token, in the following format: --executable-command="/path/to/command --foo=bar".
  • EXECUTABLE_TIMEOUT: (optional) a duration, in milliseconds, to wait for the executable to run (defaults to 30s).
  • EXECUTABLE_OUTPUT_FILE: (optional) a file path to the third-party credentials generated by the executable. This is useful for caching the credentials. The Auth libraries first check for this path before running the executable.
  • WORKFORCE_POOL_USER_PROJECT: the project number or ID that is used for quota and billing. The principal must have the serviceusage.services.use permission set on this project.

Running the command produces an OIDC IdP config file similar to the following:

{
  "type": "external_account",
  "audience": "//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID",
  "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
  "token_url": "https://sts.googleapis.com/v1/token",
  "workforce_pool_user_project": "WORKFORCE_POOL_USER_PROJECT",
  "credential_source": {
    "executable": {
      "command": "EXECUTABLE_COMMAND",
      "timeout_millis": "EXECUTABLE_TIMEOUT",
      "output_file": "EXECUTABLE_OUTPUT_FILE"
    }
  }
}

Interactive executable-sourced credentials

You can provide an executable that interacts with the user through stdin and stdout. If the user successfully signs in, the executable writes a valid, unexpired credential to the specified file.

To use this mode, the following flags are required:

  • --executable-output-file: the file that the executable writes the credential information to
  • --exeutable-interactive-timeout-millis: a non-zero value that indicates interactive mode and sets the timeout—for example, 6000 for a 60-second timeout

The following fields are required for a successful response, with the exception of expiration_time:

{
  "version": 1,
  "success": true,
  "token_type": "urn:ietf:params:oauth:token-type:id_token",
  "id_token": "HEADER.PAYLOAD.SIGNATURE",
  "expiration_time": 1620499962
}

The executable must write any errors to the file specified in --executable-output-file in the following JSON format. The following fields are all required when returning an error response.

{
  "version": 1,
  "success": false,
  "code": "401",
  "message": "Caller not authorized."
}

The code and message fields must indicate the appropriate error. These fields are used by the client libraries when raising the error.

Upon successful execution, the command returns the same fields whether interactive or non-interactive executable-sourced credentials results above.

The environment variables are also the same as a normal executable-sourced credentials.

To generate an interactive executable-sourced credential, add the parameter --executable-interactive-timeout-millis and the parameter --executable-output-file.

gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:id_token  \
    --executable-command=EXECUTABLE_COMMAND \
    --executable-interactive-timeout-millis=EXECUTABLE_INTERACTIVE_TIMEOUT \
    --executable-output-file=EXECUTABLE_OUTPUT_FILE \
    --workforce-pool-user-project=WORKFORCE_POOL_USER_PROJECT \
    --output-file /path/to/generated/config.json

Replace the following:

  • WORKFORCE_POOL_ID: the workforce pool ID.
  • PROVIDER_ID: the provider ID.
  • EXECUTABLE_COMMAND: the full command, including arguments, to run to retrieve the subject token, formatted as follows: --executable-command="/path/to/command --arg1=val1 --arg2=val2"
  • EXECUTABLE_INTERACTIVE_TIMEOUT: a duration, in milliseconds, to wait for the executable to run.
  • EXECUTABLE_OUTPUT_FILE: a file path to the third-party credentials generated by the executable. This path is useful for caching the credentials. The Auth libraries first check for this path before running the executable.
  • WORKFORCE_POOL_USER_PROJECT: the project number or ID used for quota and billing. The principal must have the serviceusage.services.use permission on this project.

Running the command produces an OIDC IdP config file similar to the following:

{
  "type": "external_account",
  "audience": "//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID",
  "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
  "token_url": "https://sts.googleapis.com/v1/token",
  "workforce_pool_user_project": "WORKFORCE_POOL_USER_PROJECT",
  "credential_source": {
    "executable": {
      "command": "EXECUTABLE_COMMAND",
      "interactive_timeout_millis": "EXECUTABLE_INTERACTIVE_TIMEOUT",
      "timeout_millis": "EXECUTABLE_TIMEOUT",
      "output_file": "EXECUTABLE_OUTPUT_FILE",
    }
  }
}

SAML

You can source the credentials that you use to set up your configuration file from the following sources:

File-sourced credentials

Assertions are loaded from a file. Another process must refresh this file with a new base64-encoded SAML assertion before the old assertion expires. For example, if the assertion has a lifetime of one hour, you must refresh the file before it is one hour old.

gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --output-file=federation_config.json \
    --credential-source-file=CREDENTIAL_FILE \
    --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \
    --workforce-pool-user-project=WORKFORCE_POOL_USER_PROJECT

Replace the following:

  • WORKFORCE_POOL_ID: the workforce pool ID.
  • PROVIDER_ID: the provider ID.
  • CREDENTIAL_FILE: the path to the credential file that is generated by the IdP.
  • WORKFORCE_POOL_USER_PROJECT: the project number or ID that is used for quota and billing. The principal must have serviceusage.services.use permission on this project.

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 base64-encoded SAML assertion or JSON containing a base64-encoded SAML assertion.

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

gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --output-file=federation_config.json \
    --credential-source-url=CREDENTIAL_URL \
    --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \
    --workforce-pool-user-project=WORKFORCE_POOL_USER_PROJECT

Replace the following:

  • WORKFORCE_POOL_ID: the workforce pool ID.
  • PROVIDER_ID: the provider ID.
  • CREDENTIAL_URL: the URL of the local server endpoint.
  • WORKFORCE_POOL_USER_PROJECT: the project number or ID used for quota and billing. The principal needs to have serviceusage.services.use permission on this project.

Executable-sourced credentials

Assertions are loaded from a local executable. The executable must provide a valid, unexpired SAML assertion in JSON format to stdout.

{
  "version": 1,
  "success": true,
  "token_type": "urn:ietf:params:oauth:token-type:saml2",
  "saml_response": "...",
  "expiration_time": 1620499962
}

These fields are required for a successful response, with the exception of expiration_time. The expiration_time field is required only when an output file is specified in the credential configuration.

If an error occurs, it must be surfaced by the executable in the following JSON format to stdout:

{
  "version": 1,
  "success": false,
  "code": "401",
  "message": "Caller not authorized."
}

These fields are all required for an error response. The code and message fields are used by the client libraries when raising the appropriate error.

The command can return the following fields:

  • version: the version of the JSON output. Only version 1 is supported.
  • success: the status of the response. When the status is true, the executable must exit with exit code 0 and the response must contain the following fields:

    • token_type: saml_response
    • expiration_time field, if an output file is specified in the credential configuration

    When the status is false, the executable must exit with a non-zero value and the response must contain the following fields: + code + message

  • token_type: the third-party subject token type, which must be urn:ietf:params:oauth:token-type:saml2

  • saml_response: the third-party SAML response

  • expiration_time: the third-party SAML response expiration time in seconds (Unix epoch time)

  • code: the error code string

  • message: the error message

The client libraries populate the following environment variables when the executable is run:

  • GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE: the audience field from the credential configuration. Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE: the expected subject token type. Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE: the output file location from the credential configuration. Only present when it is specified in the credential configuration.

To enable this credential sourcing method with the client libraries, set the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable to 1.

To generate the configuration file with a executable-sourced credential, execute the following command:

gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:saml2  \
    --executable-command=EXECUTABLE_COMMAND \
    --executable-timeout-millis=EXECUTABLE_TIMEOUT \
    --executable-output-file=EXECUTABLE_OUTPUT_FILE \
    --workforce-pool-user-project=WORKFORCE_POOL_USER_PROJECT \
    --output-file /path/to/generated/config.json

Replace the following:

  • WORKFORCE_POOL_ID: the workforce pool ID.
  • PROVIDER_ID: the provider ID.
  • EXECUTABLE_COMMAND: the full command, including arguments, to run to retrieve the subject token, in the following format: --executable-command="/path/to/command --foo=bar".
  • EXECUTABLE_TIMEOUT: (optional) the duration in milliseconds to wait for the executable to run (defaults to 30s).
  • EXECUTABLE_OUTPUT_FILE: (optional) the file path to the 3PI credentials generated by the executable. This is useful for caching the credentials. The Auth libraries check for its existence before running the executable.
  • WORKFORCE_POOL_USER_PROJECT: the project number used for quota and billing. The principal must have the serviceusage.services.use permission on this project.

Running the command produces a SAML IdP config file that is similar to the following:

{
  "type": "external_account",
  "audience": "//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID",
  "subject_token_type": "urn:ietf:params:oauth:token-type:saml2",
  "token_url": "https://sts.googleapis.com/v1/token",
  "workforce_pool_user_project": "WORKFORCE_POOL_USER_PROJECT",
  "credential_source": {
    "executable": {
      "command": "EXECUTABLE_COMMAND",
      "timeout_millis": "EXECUTABLE_TIMEOUT",
      "output_file": "EXECUTABLE_OUTPUT_FILE"
    }
  }
}

Executable-sourced credentials for gcloud interactive mode

An executable interacts with the user through the command line.

In the previous command, replace the following:

  • EXECUTABLE_OUTPUT_FILE: (required) the path to the file that provides the credentials generated by the executable.
  • EXECUTABLE_TIMEOUT: (required) a non-zero timeout value also signals the command to use interactive mode.
    {
      "version": 1,
      "success": true,
      "token_type": "urn:ietf:params:oauth:token-type:saml2",
      "saml_response": "...",
      "expiration_time": 1620499962
    }

These fields are required for a successful response, with the exception of expiration_time. Missing the expiration_time will be treat as the signal of we are going to run the executable any way.

The executable must surface any errors to the executable-output-file in the following JSON format:

{
  "version": 1,
  "success": false,
  "code": "401",
  "message": "Caller not authorized."
}

These fields are all required for an error response. The code and message fields are used by the client libraries when raising the appropriate error.

The command return fields for a success execution is exactly the same with a normal executable-sourced credentials results above.

The environment variables are also the same as a normal executable-sourced credentials.

To generate an interactive executable-sourced credential, add the parameter --executable-interactive-timeout-millis.

gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID \
    --subject-token-type=urn:ietf:params:oauth:token-type:saml2  \
    --executable-command=EXECUTABLE_COMMAND \
    --executable-interactive-timeout-millis=EXECUTABLE_INTERACTIVE_TIMEOUT \
    --executable-output-file=EXECUTABLE_OUTPUT_FILE \
    --workforce-pool-user-project=WORKFORCE_POOL_USER_PROJECT \
    --output-file /path/to/generated/config.json

Replace the following:

  • WORKFORCE_POOL_ID: the workforce pool ID.
  • PROVIDER_ID: the provider ID.
  • EXECUTABLE_COMMAND: the full command, including arguments, to run to retrieve the subject token, formatted as follows: --executable-command="/path/to/command --foo=bar").
  • EXECUTABLE_INTERACTIVE_TIMEOUT: a duration in milliseconds to wait for the executable to run.
  • EXECUTABLE_OUTPUT_FILE: a file path to the third-party credentials generated by the executable. This is useful for caching the credentials. The Auth libraries first check for this path before running the executable.
  • WORKFORCE_POOL_USER_PROJECT: the project number or ID used for quota and billing. The principal set the serviceusage.services.use permission on this project.

Running the command produces a SAML IdP config file similar to the following:

{
  "type": "external_account",
  "audience": "//iam.googleapis.com/locations/global/workforcePools/<var>WORKFORCE_POOL_ID<var>/providers/<var>PROVIDER_ID</var>",
  "subject_token_type": "urn:ietf:params:oauth:token-type:saml2",
  "token_url": "https://sts.googleapis.com/v1/token",
  "workforce_pool_user_project": "<var>WORKFORCE_POOL_USER_PROJECT</var>",
  "credential_source": {
    "executable": {
      "command": "<var>EXECUTABLE_COMMAND</var>",
      "interactive_timeout_millis": "<var>EXECUTABLE_INTERACTIVE_TIMEOUT</var>",
      "timeout_millis": "<var>EXECUTABLE_TIMEOUT</var>",
      "output_file": "<var>EXECUTABLE_OUTPUT_FILE</var>",
    }
  }
}

To sign in, run the following command:

gcloud auth login --cred-file=/path/to/config.json

Note that the CLIs (gcloud, bq) don't support executable-sourced credential types.

For headless flows, gcloud automatically uses the following scope: https://www.googleapis.com/auth/cloud-platform. gcloud then transparently posts your credentials to the Security Token Service endpoint, where it is exchanged for temporary Google Cloud access tokens.

You can now execute gcloud commands using the gcloud CLI.

Use the Google Cloud client libraries

If you use a supported client library, you can configure the client library so that it generates Google credentials automatically. When possible, we recommend that you generate credentials automatically, so that you don't need to implement the token-exchange process yourself.

Google Cloud client library support for workforce pools are supported in the following languages: Node.js, Java, Python, Go and C++ (gRPC).

To use client libraries with these services or languages, do the following:

bq

To authenticate using Workforce Identity Federation, use the gcloud auth login command:

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

where FILEPATH is the path to the credential configuration file.

Support for Workforce Identity Federation in bq is available in version 390.0.0 and later versions of the Google Cloud CLI.

C++

Most of the Google Cloud Client Libraries for C++ support Workforce 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.42.0 or later of gRPC.

The Cloud Storage Client Library for C++ uses the REST API, not gRPC, so it doesn't support Workforce Identity Federation.

auto creds = grpc::GoogleDefaultCredentials();

// Create a channel, stub and make RPC calls (same as in the previous example)
auto channel = grpc::CreateChannel("greeter.googleapis.com", creds);
std::unique_ptr<Greeter::Stub> stub(Greeter::NewStub(channel));
grpc::Status s = stub->sayHello(&context, *request, response);

gcloud

To authenticate using Workforce Identity Federation, use the gcloud auth login command:

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

where FILEPATH is the path to the credential configuration file.

Support for Workforce Identity Federation in gcloud is available in version 392.0.0 and later versions of the Google Cloud CLI.

Go

Client libraries for Go support Workforce Identity Federation if they use version v0.0.0-20211005180243-6b3c2da341f1 or later of the golang.org/x/oauth2 module.

import (
  "context"
  "fmt"
  "log"

  "cloud.google.com/go/storage"
  "google.golang.org/api/iterator"
  "google.golang.org/api/option"
  "io/ioutil"
)
ctx := context.Background()
client, err := storage.NewClient(ctx)
# Explicit initialization can also be used.
# var jsonPath = "/path/to/3p-credentials.json"
# client, err := storage.NewClient(ctx, option.WithCredentialsFile(jsonPath))
if err != nil {
  log.Fatal(err)
}
fmt.Println("Buckets:")
it := client.Buckets(ctx, projectID)
for {
  battrs, err := it.Next()
  if err == iterator.Done {
    break
  }
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(battrs.Name)
}

Java

Client libraries for Java support Workforce Identity Federation if they use version 1.2.0 or later of the com.google.auth:google-auth-library-oauth2-http artifact.

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
GoogleCredentials sourceCredentials = credentials
    .createScoped(Arrays.asList("https://www.googleapis.com/auth/devstorage.read_only"));

Storage storageService = StorageOptions.newBuilder().setProjectId("project-id")
    .setCredentials(sourceCredentials).build().getService();

Node.js

Client libraries for Node.js support Workforce Identity Federation. You must use version 7.10.0 or later of the google-auth-library package. Unlike workload identity pools, workforce pools are associated with an organization and not a Google Cloud project. When you create a GoogleAuth object, you must specify a project ID. For more information, see the README for the google-auth-library package.

const auth = new GoogleAuth({
  scopes: 'https://www.googleapis.com/auth/cloud-platform',
  // Specify a project ID.
  projectId: 'CLOUD_RESOURCE_PROJECT_ID',
});

# API request using Auth library.
const client = await auth.getClient();
const url =
    `https://storage.googleapis.com/storage/v1/b?projects=${projectId}`;
const res = await client.request({url});
console.log(res.data);

Python

Client libraries for Python support Workforce Identity Federation if they use version 2.3.0 or later of the google-auth package.

from google.cloud import storage
import google.auth

credentials, project = google.auth.default(
    scopes=['https://www.googleapis.com/auth/devstorage.read_only'])

client = storage.Client(
    project="project-id", credentials=credentials)

In the above example, the project value can be None if the library is unable to auto-discover this. You can pass it explicitly when using a service instance (as in the storage client example) or set via the environment variable GOOGLE_CLOUD_PROJECT.

For details, see the user guide for the google-auth package.

Use the REST API

You can call the Google Cloud Security Token Service API to exchange your external credentials for Google Cloud access tokens.

curl https://sts.googleapis.com/v1/token \
    --data-urlencode "audience=//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID" \
    --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
    --data-urlencode "requested_token_type=urn:ietf:params:oauth:token-type:access_token" \
    --data-urlencode "scope=https://www.googleapis.com/auth/cloud-platform" \
    --data-urlencode "subject_token_type=SUBJECT_TOKEN_TYPE" \
    --data-urlencode "subject_token=EXTERNAL_SUBJECT_TOKEN"  \
    --data-urlencode "options={\"userProject\":\"BILLING_PROJECT_NUMBER\"}"

Replace the following:

  • AUDIENCE: the full resource name of the provider that issues the subject token.
  • PROVIDER_ID: the provider ID
  • SUBJECT_TOKEN_TYPE: set to one of the following:

    • urn:ietf:params:oauth:token-type:id_token for OIDC ID tokens
    • urn:ietf:params:oauth:token-type:saml2 for SAML assertions
  • EXTERNAL_SUBJECT_TOKEN: the IdP-issued token that represents the identity of the principal for whom the access token is requested. Note: If you use OIDC the token is JWT formatted.

  • BILLING_PROJECT_NUMBER: the project number or ID used for quota and billing. The principal needs to have serviceusage.services.use permission on this project.

The response is similar to the following:

{
  "access_token": "ya29.dr.AaT61Tc6Ntv1ktbGkaQ9U_MQfiQw...",
  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
  "token_type": "Bearer",
  "expires_in": 3600
}

Manage sessions using the gcloud CLI

The temporary Google Cloud tokens that gcloud obtains from the Security Token Service endpoint expire after a specified time interval. When the token is about to expire, gcloud inspects the credentials file you provided and inspects the validity of the credentials you received from your IdP. If your credentials are still valid, gcloud proceeds to transparently obtain a new Google Cloud access token and your current session runs without interruption.

If your credentials have expired, then no new Google Cloud tokens are issued, and any calls you make with those credentials fail. At this point, you must re-authenticate.

You can terminate your session by executing the following command:

gcloud auth revoke

gcloud supports multiple user sessions. To get the list of sessions, including the currently active one, execute the following command:

gcloud auth list

The output of the command is similar to the following:

Credentialed Accounts
ACTIVE    ACCOUNT
*         bola@example.com
          principal://iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/subject/kalani@example.com

To switch to a different session and set it as active, execute the following command:

gcloud config set account principal://iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/subject/SUBJECT_ID

What's next