Configure Workload Identity Federation with X.509 certificates

This guide describes how to use Workload Identity Federation with X.509certificates that are issued by your certificate authority (CA) to authenticateto Google Cloud and access Google Cloud resources.

If your workloads possess an mTLS client certificate, you can authenticate toGoogle Cloud by registering one or more CAs with Workload Identity Federationas trust anchors. You can also register intermediate CAs.

By using Workload Identity Federation, you can let these workloadsobtain short-lived Google Cloud credentials through a mutual TLS (mTLS)connection. Workloads can use these short-lived credentials to accessGoogle Cloud APIs.

Concepts

The X.509 certificate-based federation concepts include the following:

  • Atrust anchor is a CA certificate that is consideredas the root of trust. Any client certificate chains should be chained up toone of the trust anchors.

  • Anintermediate CA is an optional certificate authority certificate thathelps build the client certificate chain.

  • Atrust store contains the trust anchor certificates and intermediateCA certificates that are used to validate theclient certificate chain. A CA issues trusted certificates forthe client.

    You can upload the following types of client certificates to the trust store:

    • Certificates issued by third-party CAs of your choice
    • Certificates issued by your private CAs
    • Signed certificates, as described inCreate self-signed certificates

Before you begin

To start configuring Workload Identity Federation, do the following:

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.

    Go to project selector

  2. We recommend that youuse a dedicated project to manage workload identity pools and providers.
  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the IAM, Resource Manager, Service Account Credentials, and Security Token Service APIs.

    Roles required to enable APIs

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

    Enable the APIs

Required roles

To get the permissions that you need to configure Workload Identity Federation, ask your administrator to grant you the following IAM roles on the project:

For more information about granting roles, seeManage access to projects, folders, and organizations.

You might also be able to get the required permissions throughcustom roles or otherpredefined roles.

Alternatively, the IAM Owner (roles/owner) basicrole also includes permissions to configure identity federation.You should not grant basic roles in a production environment, but you can grant them in adevelopment or test environment.

Create a trust store

This section shows you how to create a trust store. At a high level, the stepsare as follows:

Generate self-signed certificates

This section shows you how to generate keys and create signed certificates. If you have already created certificates, you can skipthis section and continue withFormat the certificates.

This section usesopenssl commands to create root and intermediatecertificates.

To generate a root certificate and a signedintermediate certificate with validkeyUsage andextendedKeyUsage fields, dothe following:

  1. Create anopenssl configuration file to create your signing certificates.At minimum, the file is similar to the following, but you can set additionalfields as needed.

    cat >example.cnf <<EOF[req]distinguished_name=empty_distinguished_name[empty_distinguished_name]# Kept empty to allow setting via -subj command-line argument.[ca_exts]basicConstraints=critical,CA:TRUEkeyUsage=keyCertSignextendedKeyUsage=clientAuth[leaf_exts]keyUsage=critical,DigitalSignature,KeyEnciphermentbasicConstraints=critical,CA:FALSEEOF
  2. Create the root certificate.

    opensslreq-x509\-new-sha256-newkeyrsa:2048-nodes\-days3650-subj'/CN=root'\-configexample.cnf\-extensionsca_exts\-keyoutroot.key-outroot.cert
  3. Create the signing request for the intermediate certificate.

    opensslreq\-new-sha256-newkeyrsa:2048-nodes\-subj'/CN=int'\-configexample.cnf\-extensionsca_exts\-keyoutint.key-outint.req
  4. Create the intermediate certificate.

    opensslx509-req\-CAkeyroot.key-CAroot.cert\-set_serial1\-days3650\-extfileexample.cnf\-extensionsca_exts\-inint.req-outint.cert
  5. Create the signing request for leaf certificate.

    opensslreq-new-sha256-newkeyrsa:2048-nodes\-subj'/CN=example'\-configexample.cnf\-extensionsleaf_exts\-keyoutleaf.key-outleaf.req
  6. Create the leaf certificate issued by the intermediate.

    opensslx509-req\-CAkeyint.key-CAint.cert\-set_serial1-days3650\-extfileexample.cnf\-extensionsleaf_exts\-inleaf.req-outleaf.cert

Format the certificates

To include new or existing certificates in a trust store, format the certificates into a one-line string,and store them in environment variables. Thecertificates must be PEM formatted. To format the certificates and store them in environment variables,do the following:

  1. Save the root certificate as a one-line string.

    exportROOT_CERT=$(catroot.cert|sed's/^[ ]*//g'|sed-z'$ s/\n$//'|tr'\n'$|sed's/\$/\\n/g')
  2. Save an intermediate certificate as a one-line string.

    exportINTERMEDIATE_CERT=$(catint.cert|sed's/^[ ]*//g'|sed-z'$ s/\n$//'|tr'\n'$|sed's/\$/\\n/g')

Create the trust store

In this section, you create a trust store using a YAML-formatted file that contains your trust anchors and intermediate CAs.

This file contains the certificate content from the environment variablesthat you created inFormat the certificates. To add additionaltrust anchors, add additionaltrustAnchors entries undertrustStore.To add additional intermediate CA certificates, add additionalintermediateCas entries undertrustStore.

To create the trust store file, run the following command:

cat <<EOF >trust_store.yamltrustStore:trustAnchors:-pemCertificate:"${ROOT_CERT}"intermediateCas:-pemCertificate:"${INTERMEDIATE_CERT}"EOF

Define an attribute mapping and condition

The client X.509 certificate can contain multiple attributes.You must select which attribute you want to use as the subject identifier by mappinggoogle.subject in Google Cloud to the attribute from your certificate.For example, if the attribute in the certificate isthe subject common name, then the mapping would be as follows:google.subject=assertion.subject.dn.cn

Optionally, you canmap additional attributes.You can then refer to these attributes when granting access to resources.

Your attribute mappings can use the attributes within the clientcertificate, including the following:

  • serialNumberHex: the serial number
  • subject.dn.cn: the subject common name
  • subject.dn.o: the subject organization name
  • subject.dn.ou: the subject last organization unit
  • issuer.dn.cn: the issuer common name
  • issuer.dn.o: the issuer organization name
  • issuer.dn.ou: the issuer last organization unit
  • san.dns: the subject alternative name's first DNS name
  • san.uri: the subject alternative name's first URI
  • sha256Fingerprint: SHA256 leaf certificate hash (Base64)

You must map one of these attributes togoogle.subject to uniquely identifythe subject. To protect against spoofing threats, choose an attribute with a uniquevalue that can't be changed. By default, thegoogle.subject identifier isset to the client certificate subject common name,assertion.subject.dn.cn.

Optionally, you can define anattribute condition.Attribute conditions are CEL expressions that can check assertion attributes andtarget attributes. If the attribute condition evaluates totrue for a givencredential, the credential is accepted. Otherwise, the credential is rejected.

Warning: Although you can grant access to all of the identities in a workloadidentity pool, doing so can incur risk, especially when the trust anchorscontain a well-known public root CA. We recommend that you limit accessusingattribute condition.

You can use an attribute condition to restrict which subjectscan use Workload Identity Federation to obtain short-lived Google Cloudtokens.

For example, the following condition restricts access to client certificatescontaining SPIFFE IDspiffe://example/path:

assertion.san.uri=="spiffe://example/path"

Configure Workload Identity Federation

This section shows you how to configure a workload identity pool and a workload identitypool provider. You need only perform these steps once for each trust store.You can then use the same workload identity pool and provider for multipleworkloads and across multiple Google Cloud projects.

Create the workload identity pool

  1. To create a new workload identity pool, execute the following command:

    gcloud iam workload-identity-pools createPOOL_ID \    --location="global" \    --description="DESCRIPTION" \    --display-name="DISPLAY_NAME"

    Replace the following:

    • POOL_ID: the unique ID for the pool.
    • DISPLAY_NAME: the name of the pool.
    • DESCRIPTION: a description of the pool thatyou choose. This description appears when you grant access to poolidentities.

Create the workload identity pool provider

  1. To add an X.509 workload identity pool provider, run the followingcommand:

    gcloud iam workload-identity-pools providers create-x509PROVIDER_ID \    --location=global \    --workload-identity-pool="POOL_ID" \    --trust-store-config-path="TRUST_STORE_CONFIG" \    --attribute-mapping="MAPPINGS" \    --attribute-condition="CONDITIONS"

    Replace the following:

    • PROVIDER_ID: A unique workload identitypool provider ID of your choice.
    • POOL_ID: The workload identity pool IDthat you created earlier.
    • TRUST_STORE_CONFIG: The trust store YAML file.
    • MAPPINGS: A comma-separated list ofattribute mappings that you createdearlier in this guide. For example,google.subject=assertion.subject.dn.cn.
    • CONDITIONS: Optional. Anattribute conditionthat you created earlier in this guide. Remove the parameter ifyou don't have an attribute condition.

Configure Context-Aware Access Policy Enforcement for Workload Identity Federation

You can strengthen resource security against token replay attacks byenabling Context-Aware Access, which enforces mTLS validation for access requests. In this process, an mTLS binding incorporates policies based on the transport context and uses the state of the client's certificate within the TLS session to make authorization decisions. For X.509 workload identity federation, an mTLS binding ensures that the entire authentication flow is securely tied to a trusted workload. This mitigates the risk of credential theft, because the authentication is bound to a specific, trusted endpoint.

Authenticate a workload

You must perform these steps once for each workload.

Allow your external workload to access Google Cloud resources

To provide your workload with access to Google Cloud resources, werecommend that you grant direct resource access to the principal. In this case,the principal is the federated user. Some Google Cloud products haveGoogle Cloud API limitations.If your workload calls an API endpoint that has a limitation, you can insteaduse service account impersonation. In this case, the principal is theGoogle Cloud service account, which acts as the identity. You grant accessto the service account on the resource.

Direct resource access

You can grant access to a federated identity directly on resources by usingthe Google Cloud console or the gcloud CLI.

Console

To use the Google Cloud console to grant IAM rolesdirectly on a resource, you must go to the resource's page, and thengrant the role. The following example shows you how to goto the Cloud Storage page and grant the role Storage Object Viewer(roles/storage.objectViewer) to a federated identity directly on aCloud Storage bucket.

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket for which youwant to grant the role.

  3. Select thePermissions tab near the top of the page.

  4. Click theGrant access button.

    TheAdd principals dialog appears.

  5. In theNew principals field, enter one or more identitiesthat need access to your bucket.

    By subject

    principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT

    Replace the following:

    • PROJECT_NUMBER: the projectnumber
    • POOL_ID: the workloadpool ID
    • SUBJECT: the individualsubject mapped from your IdP—for example,administrator@example.com

    By group

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

    Replace the following:

    • PROJECT_NUMBER: the projectnumber
    • WORKLOAD_POOL_ID: the workloadpool ID
    • GROUP: the groupmapped from your IdP—for example:administrator-group@example.com

    By attribute

    principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE

    Replace the following:

    • PROJECT_NUMBER: the projectnumber
    • WORKLOAD_POOL_ID: the workloadpool ID
    • ATTRIBUTE_NAME: one of theattributes that was mapped from your IdP
    • ATTRIBUTE_VALUE: the valueof the attribute
  6. Select a role (or roles) from theSelect a role drop-down menu.The roles you select appear in the pane with a short description ofthe permissions they grant.

  7. ClickSave.

gcloud

To use the gcloud CLI to grant IAM roles on aresource in a project, do the following:

  1. Obtain the project number of the project in which the resourceis defined.

    gcloud projects describe $(gcloud config get-value core/project) --format=value\(projectNumber\)
  2. Grant access to the resource.

    To use the gcloud CLI to grant the role Storage Object Viewer (roles/storage.objectViewer) to external identities that meet certain criteria, run the following command.

    By subject

    gcloud storage buckets add-iam-policy-bindingBUCKET_ID \    --role=roles/storage.objectViewer \    --member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT"

    By group

    gcloud storage buckets add-iam-policy-bindingBUCKET_ID \    --role=roles/storage.objectViewer \    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/group/GROUP"

    By attribute

    gcloud storage buckets add-iam-policy-bindingBUCKET_ID \    --role=roles/storage.objectViewer \    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE"

    Replace the following:

    • BUCKET_ID:the bucket on which to grant access
    • PROJECT_NUMBER: theproject number.of the project that contains the workload identity pool
    • POOL_ID: the pool ID of the workload identity pool
    • SUBJECT: the expected value for the attribute thatyou've mappedtogoogle.subject
    • GROUP: the expected value for the attribute thatyou've mappedtogoogle.groups
    • ATTRIBUTE_NAME: the name of a custom attribute inyour attribute mapping
    • ATTRIBUTE_VALUE: the value of the custom attribute in your attribute mapping

    You can grant roles on any Google Cloud resource that supportsIAM allow policies.

    Note: You must use the project number, not the project ID, in themember identifier.

Service account impersonation

  1. To create a service account for the external workload, do the following:

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

      Roles required to enable APIs

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

      Enable the APIs

    2. Create a service accountthat represents the workload. We recommend that youuse a dedicated service account for each workload.The service account doesn't need to be in the same project as theworkload identity pool, but you must refer to the project thatcontains the service account.

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

  2. To let the federated identity impersonate the service account, do thefollowing:

Console

To use the Google Cloud console to grant IAM rolesto a federated identity with service account, do the following:

Service Account in the same project

  1. To grant access using service account impersonation for aservice account in the same project, do the following:

    1. Go to theWorkload Identity Pools page.

      Go to Workload Identity Pools

    2. SelectGrant access.

    3. In theGrant access to service account dialog, selectGrant access using Service Account impersonation.

    4. In theService accounts list, select theservice account for the external identities to impersonate,and do the following:

    5. To choose which identities in the pool can impersonate theservice account, perform one of the following actions:

      • To allow only specific identities of the workloadidentity pool to impersonate the service account, selectOnly identities matching the filter.

      • In theAttribute name list, select the attributethat you want to filter on.

      • In theAttribute value field, enter the expectedvalue of the attribute; for example, if you use anattribute mappinggoogle.subject=assertion.sub, setAttribute name tosubject andAttribute valueto the value of thesub claim in tokens that areissued by your external identity provider.

    6. To save the configuration, clickSave and thenDismiss.

Service account in a different project

Note: Service accounts from different projects won't appear in the"CONNECTED SERVICE ACCOUNTS" section of yourWorkload Identity Pool.
  1. To grant access using service account impersonation for aservice account in a different project, do the following:

    1. Go to theService Accounts page.

      Go to Service Accounts

    2. Select the service account that you want to impersonate.

    3. ClickManage access.

    4. ClickAdd principal.

    5. In theNew principal field, enter one of the followingprincipal identifiersfor the identities in your pool that will impersonate theservice account.

      By subject

      principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT

      Replace the following:

      • PROJECT_NUMBER: the projectnumber
      • POOL_ID: the workloadpool ID
      • SUBJECT: the individualsubject mapped from your IdP—for example,administrator@example.com

      By group

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

      Replace the following:

      • PROJECT_NUMBER: the projectnumber
      • WORKLOAD_POOL_ID: the workloadpool ID
      • GROUP: the groupmapped from your IdP—for example:administrator-group@example.com

      By attribute

      principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE

      Replace the following:

      • PROJECT_NUMBER: the projectnumber
      • WORKLOAD_POOL_ID: the workloadpool ID
      • ATTRIBUTE_NAME: one of theattributes that was mapped from your IdP
      • ATTRIBUTE_VALUE: the valueof the attribute

      By pool

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

      Replace the following:

      • PROJECT_NUMBER: the projectnumber
      • WORKLOAD_POOL_ID: the workloadpool ID
    6. InSelect a role, select the Workload Identity Userrole (roles/iam.workloadIdentityUser).

    7. To save the configuration, clickSave.

gcloud

To grant the Workload Identity User role (roles/iam.workloadIdentityUser) to a federated principal or principal set, run the following command. To learn more about Workload Identity Federation principal identifiers, seePrincipal types.

By subject

gcloud iam service-accounts add-iam-policy-bindingSERVICE_ACCOUNT_EMAIL \    --role=roles/iam.workloadIdentityUser \    --member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT"

By group

gcloud iam service-accounts add-iam-policy-bindingSERVICE_ACCOUNT_EMAIL \    --role=roles/iam.workloadIdentityUser \    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/group/GROUP"

By attribute

gcloud iam service-accounts add-iam-policy-bindingSERVICE_ACCOUNT_EMAIL \    --role=roles/iam.workloadIdentityUser \    --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.ATTRIBUTE_NAME/ATTRIBUTE_VALUE"

Replace the following:

  • SERVICE_ACCOUNT_EMAIL:the email address of the service account
  • PROJECT_NUMBER: theproject number.of the project that contains the workload identity pool
  • POOL_ID: the pool ID of the workload identity pool
  • SUBJECT: the expected value for the attribute thatyou've mappedtogoogle.subject
  • GROUP: the expected value for the attribute thatyou've mappedtogoogle.groups
  • ATTRIBUTE_NAME: the name of a custom attribute inyour attribute mapping
  • ATTRIBUTE_VALUE: the value of the custom attribute in your attribute mapping

Note: You must use the project number, not the project ID, in themember identifier.

Download or create a credential configuration

TheCloud Client Libraries and thegcloud CLI can automatically obtain externalcredentials and use these credentials to impersonate a service account. Tolet libraries and tools complete this process, you must provide a credentialconfiguration file. This file provides the following information:

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

Additionally, for X.509 certificate federation, a certificate configuration fileis required. This file contains paths to the X.509 client certificate and privatekey files.

Note: Unlike aservice account key,a credential configuration file doesn't contain a private key and doesn't needto be kept confidential. For the credential configuration file details, seeAIP-4117: External Account Credentials (Workload Identity Federation).

Create credential and certificate configuration files that let the library obtainaccess tokens using X.509 certificates.

Direct resource access

To create credential and certificate configuration files for direct resource access by usinggcloud iam workload-identity-pools create-cred-config,do the following:

gcloud iam workload-identity-pools create-cred-config \  projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \    --credential-cert-path=CLIENT_CERT_PATH \    --credential-cert-private-key-path=CLIENT_PRIVATE_KEY_PATH \    --credential-cert-trust-chain-path=TRUST_CHAIN_PATH \    --output-file=FILEPATH.json

Replace the following:

  • PROJECT_NUMBER: The project number of theproject that contains the workload identity pool.
  • POOL_ID: The ID of the workload identitypool.
  • PROVIDER_ID: The ID of the workloadidentity pool provider.
  • CLIENT_CERT_PATH: The path of the clientcertificate file.
  • CLIENT_PRIVATE_KEY_PATH: The path of the clientcertificate private key file.
  • TRUST_CHAIN_PATH: Optional. The path of thetrust chain file that contains any intermediate certificates that are notconfigured in x509 provider.
  • FILEPATH: The file to save the configurationto.

Running this command will also create a certificate configuration file andstore it at the default gcloud CLI location:

  • Linux and macOS:~/.config/gcloud/certificate_config.json

  • Windows:%APPDATA%\gcloud\certificate_config.json

Service account impersonation

To create credential and certificate configuration files with service account impersonation by usinggcloud iam workload-identity-pools create-cred-config,do the following:

gcloud iam workload-identity-pools create-cred-config \  projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID \    --service-account=SERVICE_ACCOUNT_EMAIL \    --service-account-token-lifetime-seconds=SERVICE_ACCOUNT_TOKEN_LIFETIME \    --credential-cert-path=CLIENT_CERT_PATH \    --credential-cert-private-key-path=CLIENT_KEY_PATH \    --credential-cert-trust-chain-path=TRUST_CHAIN_PATH \    --output-file=FILEPATH.json

Replace the following:

  • PROJECT_NUMBER: The project number of theproject that contains the workload identity pool.
  • POOL_ID: The ID of the workload identitypool.
  • PROVIDER_ID: The ID of the workloadidentity pool provider.
  • SERVICE_ACCOUNT_EMAIL: If you use serviceaccount impersonation, replace with the email addressof the service account.
  • SERVICE_ACCOUNT_TOKEN_LIFETIME: The lifetime of theservice account access token, in seconds, if you useservice account impersonation. If omitted, this lifetime defaults to one hour.Omit this flag if you don't use service account impersonation. To specify alifetime longer than one hour, you must configure theconstraints/iam.allowServiceAccountCredentialLifetimeExtensionorganizational policy constraint.
  • CLIENT_CERT_PATH: The path of the clientcertificate file.
  • CLIENT_PRIVATE_KEY_PATH: The path of the clientcertificate private key file.
  • TRUST_CHAIN_PATH: Optional. The path of thetrust chain file that contains any intermediate certificates notconfigured in x509 provider.
  • FILEPATH: The file to save configurationto.

Running this command will also create a certificate configuration file andstore it at the default Google Cloud CLI location:

  • Linux and macOS:~/.config/gcloud/certificate_config.json

  • Windows:%APPDATA%\gcloud\certificate_config.json

Use the credential configuration to access Google Cloud

To let tools and client libraries use your credential configuration, do thefollowing. To learn more about Application Default Credentials, seeHowApplication Default Credentialsworks.

  1. Initialize an environment variableGOOGLE_APPLICATION_CREDENTIALS and set it to the credential configuration file:

    Bash

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

    PowerShell

      $env:GOOGLE_APPLICATION_CREDENTIALS = Resolve-Path 'FILEPATH.json'
    ReplaceFILEPATH with the relative path to the credential configuration file.
  2. Ensure that the client library can find the certificate configuration file.The certificate configuration file is located at one of the following paths:

    • The default gcloud CLI path:

      • Linux and macOS:~/.config/gcloud/certificate_config.json

      • Windows:%APPDATA%\gcloud\certificate_config.json

    • The path set in theGOOGLE_API_CERTIFICATE_CONFIG environment variable.

  3. Use the following Cloud Client Libraries that support Workload Identity Federationwith X.509 certificates.

    Go

    Client libraries for Go support X.509 Workload Identity Federation if theyuse version 0.16.0 or later of thecloud.google.com/go/auth module andversion 0.189.0 of thegoogle.golang.org/api module.

    To check which version of these modules your client library uses, run thefollowing command while in the directory containing the go.mod file for yourmodule:

    golist-mcloud.google.com/go/authgolist-mcloud.google.com/api

    Python

    Client libraries for Python support X.509 Workload Identity Federation if they use version2.39.0 or later of thegoogle-auth package

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

    pipshowgoogle-auth

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

  4. If your workload runs on macOS, setCLOUDSDK_PYTHON_SITEPACKAGES=1to configure gcloud CLI to use Python libraries outside of itsinstallation directory.

  5. To authenticate using the gcloud CLI, run the followingcommand:

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

    ReplaceFILEPATH with the path to thecredential configuration file.

    Support for X.509 Workload Identity Federation in gcloud CLI is available inversion 538.0 and later versions of the gcloud CLI.

Obtain an access token using plain request to access Google Cloud

Create the trust chain

This step shows you how to create the trust chain. You pass the trust chain in thesubject_token field when calling Security Token Service in plain request.

Format the certificates that need to be includedin the chain as a JSON-formatted list as specified inRFC 7515.The leaf certificate used for the mTLS handshake must be specified as the firstitem. Each certificate in the bundle should be a base64-encoded string.

  1. Save the leaf certificate and the intermediate certificate to base64-encoded strings.

    exportLEAF_CERT=$(opensslx509-inleaf.cert-outleaf.der-outformDER &&catleaf.der|opensslenc-base64-A)
    exportINTERMEDIATE_CERT=$(opensslx509-inint.cert-outint.der-outformDER &&catint.der|opensslenc-base64-A)
  2. Create a JSON-formatted list of strings that can be passed assubject_token in the call to Security Token Service, later in this document.

    exportTRUST_CHAIN="[\\\"${LEAF_CERT}\\\", \\\"${INTERMEDIATE_CERT}\\\"]"

Obtain access token

To obtain the access token, do the following:

  1. Perform token exchange with mTLS and the client certificate:

    curl --keyCLIENT_CERT_KEY \--certCLIENT_CERT \--request POST 'https://sts.mtls.googleapis.com/v1/token' \--header "Content-Type: application/json" \--data-raw '{    "subject_token_type": "urn:ietf:params:oauth:token-type:mtls",    "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",    "audience": "WORKLOAD_IDENTITY_POOL_URI",    "requested_token_type": "urn:ietf:params:oauth:token-type:access_token",    "scope": "https://www.googleapis.com/auth/cloud-platform",    "subject_token": "TRUST_CHAIN"}'

    Replace the following:

    • CLIENT_CERT_KEY: the client certificate private key
    • CLIENT_CERT: the client certificate
    • WORKLOAD_IDENTITY_POOL_URI: the URL of the workloadidentity pool provider in the following format:

      //iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID

    • TRUST_CHAIN: The trust chain needed to verifythe leaf certificate, must at least includeCLIENT_CERT as the first item. If you followedinstructions inFormatting the certificates section, replaceTRUST_CHAINwith'"${TRUST_CHAIN}"'

  2. Use the bearer access token generated in the previous step to accessGoogle Cloud resources—for example:

    curl-XGET'https://storage.googleapis.com/my_object'-H"Authorization: Bearer$ACCESS_TOKEN"

Limits

The following table lists limits.

ItemLimitNotes
Number of trust anchors3Each certificate must not exceed 32 KB.
Number of intermediate certificates10Each certificate shouldn't exceed 32 KB.
Number of name constraints allowed during validation of root and intermediate certificates10
Intermediate certificates that share the same Subject and Subject Public Key information5This limit is for each trust store.
Certificate chain depth5The maximum depth for a certificate chain, including the root and client certificates.
Number of times intermediate certificates can be evaluated when attempting to build the chain of trust100
Keys of certificates uploaded and passed from the client

RSA keys can be from 2048 to 4096 bits.

ECDSA certificates must use either P-256 or P-384 curves.

RSA-2048 and P-256 are recommended for normal use cases, use others for best security practice.
Maximum leaf certificate lifetime390 days.Leaf certificate issued longer than 390 days will be rejected.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.