Configure Workload Identity Federation with X.509 certificates Stay organized with collections Save and categorize content based on your preferences.
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:
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.createpermission.Learn how to grant roles.
We recommend that youuse a dedicated project to manage workload identity pools and providers.Verify that billing is enabled for your Google Cloud project.
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.
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:
- Workload Identity Pool Admin (
roles/iam.workloadIdentityPoolAdmin) - Service Account Admin (
roles/iam.serviceAccountAdmin)
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:
Create an
opensslconfiguration 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:FALSEEOFCreate the root certificate.
opensslreq-x509\-new-sha256-newkeyrsa:2048-nodes\-days3650-subj'/CN=root'\-configexample.cnf\-extensionsca_exts\-keyoutroot.key-outroot.certCreate the signing request for the intermediate certificate.
opensslreq\-new-sha256-newkeyrsa:2048-nodes\-subj'/CN=int'\-configexample.cnf\-extensionsca_exts\-keyoutint.key-outint.reqCreate the intermediate certificate.
opensslx509-req\-CAkeyroot.key-CAroot.cert\-set_serial1\-days3650\-extfileexample.cnf\-extensionsca_exts\-inint.req-outint.certCreate the signing request for leaf certificate.
opensslreq-new-sha256-newkeyrsa:2048-nodes\-subj'/CN=example'\-configexample.cnf\-extensionsleaf_exts\-keyoutleaf.key-outleaf.reqCreate 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:
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')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}"EOFDefine 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 numbersubject.dn.cn: the subject common namesubject.dn.o: the subject organization namesubject.dn.ou: the subject last organization unitissuer.dn.cn: the issuer common nameissuer.dn.o: the issuer organization nameissuer.dn.ou: the issuer last organization unitsan.dns: the subject alternative name's first DNS namesan.uri: the subject alternative name's first URIsha256Fingerprint: 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.
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
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
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.
- In the Google Cloud console, go to the Cloud StorageBuckets page.
In the list of buckets, click the name of the bucket for which youwant to grant the role.
Select thePermissions tab near the top of the page.
Click theadd_boxGrant access button.
TheAdd principals dialog appears.
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/SUBJECTReplace the following:
PROJECT_NUMBER: the projectnumberPOOL_ID: the workloadpool IDSUBJECT: 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/GROUPReplace the following:
PROJECT_NUMBER: the projectnumberWORKLOAD_POOL_ID: the workloadpool IDGROUP: 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_VALUEReplace the following:
PROJECT_NUMBER: the projectnumberWORKLOAD_POOL_ID: the workloadpool IDATTRIBUTE_NAME: one of theattributes that was mapped from your IdPATTRIBUTE_VALUE: the valueof the attribute
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.
ClickSave.
gcloud
To use the gcloud CLI to grant IAM roles on aresource in a project, do the following:
Obtain the project number of the project in which the resourceis defined.
gcloud projects describe $(gcloud config get-value core/project) --format=value\(projectNumber\)
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 accessPROJECT_NUMBER: theproject number.of the project that contains the workload identity poolPOOL_ID: the pool ID of the workload identity poolSUBJECT: the expected value for the attribute thatyou've mappedtogoogle.subjectGROUP: the expected value for the attribute thatyou've mappedtogoogle.groupsATTRIBUTE_NAME: the name of a custom attribute inyour attribute mappingATTRIBUTE_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
To create a service account for the external workload, do the following:
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.enablepermission.Learn how to grant roles.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.
Grant the service account accessto resources that you want external identities to access.
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
To grant access using service account impersonation for aservice account in the same project, do the following:
Go to theWorkload Identity Pools page.
SelectGrant access.
In theGrant access to service account dialog, selectGrant access using Service Account impersonation.
In theService accounts list, select theservice account for the external identities to impersonate,and do the following:
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 mapping
google.subject=assertion.sub, setAttribute name tosubjectandAttribute valueto the value of thesubclaim in tokens that areissued by your external identity provider.
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.To grant access using service account impersonation for aservice account in a different project, do the following:
Go to theService Accounts page.
Select the service account that you want to impersonate.
ClickManage access.
ClickAdd principal.
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/SUBJECTReplace the following:
PROJECT_NUMBER: the projectnumberPOOL_ID: the workloadpool IDSUBJECT: 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/GROUPReplace the following:
PROJECT_NUMBER: the projectnumberWORKLOAD_POOL_ID: the workloadpool IDGROUP: 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_VALUEReplace the following:
PROJECT_NUMBER: the projectnumberWORKLOAD_POOL_ID: the workloadpool IDATTRIBUTE_NAME: one of theattributes that was mapped from your IdPATTRIBUTE_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 projectnumberWORKLOAD_POOL_ID: the workloadpool ID
InSelect a role, select the Workload Identity Userrole (
roles/iam.workloadIdentityUser).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 accountPROJECT_NUMBER: theproject number.of the project that contains the workload identity poolPOOL_ID: the pool ID of the workload identity poolSUBJECT: the expected value for the attribute thatyou've mappedtogoogle.subjectGROUP: the expected value for the attribute thatyou've mappedtogoogle.groupsATTRIBUTE_NAME: the name of a custom attribute inyour attribute mappingATTRIBUTE_VALUE: the value of the custom attribute in your attribute mapping
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.jsonWindows:
%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.jsonWindows:
%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.
Initialize an environment variable
GOOGLE_APPLICATION_CREDENTIALSand set it to the credential configuration file:Bash
Replaceexport GOOGLE_APPLICATION_CREDENTIALS=`pwd`/FILEPATH.json
FILEPATHwith the relative path to the credential configuration file.PowerShell
Replace$env:GOOGLE_APPLICATION_CREDENTIALS = Resolve-Path 'FILEPATH.json'
FILEPATHwith the relative path to the credential configuration file.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.jsonWindows:
%APPDATA%\gcloud\certificate_config.json
The path set in the
GOOGLE_API_CERTIFICATE_CONFIGenvironment variable.
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 the
cloud.google.com/go/authmodule andversion 0.189.0 of thegoogle.golang.org/apimodule.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/apiPython
Client libraries for Python support X.509 Workload Identity Federation if they use version2.39.0 or later of the
google-authpackageTo check which version of this package your client library uses, run thefollowing command in the environment where the package is installed:
pipshowgoogle-authTo specify a project ID for the authentication client, you can set the
GOOGLE_CLOUD_PROJECTenvironment 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-authpackage.If your workload runs on macOS, set
CLOUDSDK_PYTHON_SITEPACKAGES=1to configure gcloud CLI to use Python libraries outside of itsinstallation directory.To authenticate using the gcloud CLI, run the followingcommand:
gcloud auth login --cred-file=FILEPATH.json
Replace
FILEPATHwith 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.
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)Create a JSON-formatted list of strings that can be passed as
subject_tokenin 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:
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 keyCLIENT_CERT: the client certificateWORKLOAD_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_IDTRUST_CHAIN: The trust chain needed to verifythe leaf certificate, must at least includeCLIENT_CERTas the first item. If you followedinstructions inFormatting the certificates section, replaceTRUST_CHAINwith'"${TRUST_CHAIN}"'
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.
| Item | Limit | Notes |
|---|---|---|
| Number of trust anchors | 3 | Each certificate must not exceed 32 KB. |
| Number of intermediate certificates | 10 | Each certificate shouldn't exceed 32 KB. |
| Number of name constraints allowed during validation of root and intermediate certificates | 10 | |
| Intermediate certificates that share the same Subject and Subject Public Key information | 5 | This limit is for each trust store. |
| Certificate chain depth | 5 | The 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 trust | 100 | |
| 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 lifetime | 390 days. | Leaf certificate issued longer than 390 days will be rejected. |
What's next
- Read more aboutWorkload Identity Federation.
- Learn aboutbest practices for using Workload Identity Federation.
- See how you canmanage workload identity pools and providers.
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.