Configure Workload Identity Federation with other identity providers Stay organized with collections Save and categorize content based on your preferences.
To authenticate to Google Cloud, you can let the workload exchangeits environment-specific credentials for short-lived Google Cloudcredentials by using Workload Identity Federation.
Workloads that run outside of Google Cloud might have access to existing,environment-specific credentials, for example:
A workload might be able to obtain an OpenID Connect (OIDC) assertion tokenfrom an identity provider (IdP).
A workload might be able to obtain a SAML assertion token from an identityprovider (IdP).
Using Workload Identity Federation can help youreduce the number of credentials that require rotation.
The following sections describe how you can use Workload Identity Federation withIdPs that support either OpenID Connect (OIDC) or SAML authentication protocols.
Note: If your workloads run on AWS or Azure, seeConfigure Workload Identity Federation with AWS or Azure instead. If you'reusing Active Directory Federation Services (AD FS) as IdP, seeConfigure Workload Identity Federation with Active Directory.Prepare your external IdP
You need to perform these steps once for each IdP.
Before you begin, verify that your external IdP meets the followingrequirements:
OIDC
The IdP supports OpenID Connect 1.0.
The IdP has an issuer URI.
Google Cloud can access aJSON web key set (JWKS)that containsJSON web keys (JWKs).The JWKs are used to validate OIDC assertion tokens. You can provideaccess to the JWKS through one of the following methods:
Google Cloud downloadsOIDC metadata from the IdP, through a publicly available, well-known,internet-accessible discovery URL. Within the metadata, the JWKS URLmust be secured with SSL and TLS. The JWKS URL must start with
https://. Google Cloud doesn't support JWKS URLs that aresecured with self-signed certificates.Google Cloud uses these endpoint URLs to download your IdP'sJSON web keys (JWKs) and uses these keys to validate tokens.Google Cloud doesn't limit the number of keys that it candownload.
You can upload an OIDC JWKS file directly to Google Cloud whenyou create or update the OIDC workload identity pool provider. To dothis, you use the
--jwk-json-pathto provide a path to your JWKSfile. You can use this method when the IdP's OIDC metadata endpointURL isn't publicly accessible. A maximum of 8 keyscan be uploaded to Google Cloud.
SAML
The IdP supports SAML 2.0.
The IdP provides aSAML SP metadata document that describes the SAML service provider configuration and contains theIdP's signing certificate.
Google Cloud uses this certificate to validate SAML assertions andresponses.
The IdP signing certificate must contain either an ECDSA or RSA keythat is within anX.509 v3 certificate.
Recommended signing algorithms include the following:
- ECDSAwithSHA256
- RSAwithSHA256with supported key sizes of 2048, 3072, and 4096 bits.
The signing certificate must meet the following validity requirements:
notBefore: a timestamp that is no more than 7 days in the futurenotAfter: a timestamp that is no more than 25 years in the future
You can configure a SAML workload identity pool provider with at most threeSAML signing certificates at a given time. This limitation doesn't apply toother workload identity pool provider types, like OIDC and X.509. Whenmultiple certificates exist, Google Cloud iterates through them andattempts to use each non-expired certificate to fulfill a token exchangerequest.
As a security best practice, we strongly recommend that you don't reuse thesame key pair with other services.
If your IdP meets these criteria, do the following:
OIDC
Configure your IdP so that your workload can obtain ID tokens that meetthe following criteria:
- Tokens are signed using the
RS256orES256algorithm. Tokens contain an
audclaim with the following value:https://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/WORKLOAD_PROVIDER_ID
Replace the following:
PROJECT_NUMBER: theproject numberof the Google Cloud project that you use to create workload identity pool.POOL_ID: an ID of your choice thatidentifies the workload identity pool. You must use the same IDwhen creating the workload identity pool later.WORKLOAD_PROVIDER_ID: an ID of your choicethat identifies the workload identity pool provider. You must usethe same ID when creating the workload identity pool provider later.
Alternatively, you can configure the workload identity pool provider toexpect a custom audience.
Tokens contain an
expclaim that is in the future and aniatclaimthat is in the past.The value of
expmust be greater than the value ofiatby at most24 hours.
Typically, it's best to use ID tokens when performing a token exchange,because ID tokens reflect the user's identity. If you decide to useaccess tokens instead, make sure that access tokens meet the followingadditional requirements:
- Access tokens areJSON Web Token-formatted
Access tokens contain an
ISSUERclaim so that theURLISSUER/.well-known/openid-configurationpointsto the IdP's OIDC metadata endpoint.To upload local JWK keys, seeManage OIDC JWKs.
SAML
Configure your IdP so that SAML assertions contain elements that meet thefollowing criteria:
- an
Issuerelement that is set to the Entity ID configured in theworkload identity pool provider. The issuer format must be omitted or set tourn:oasis:names:tc:SAML:2.0:nameid-format:entity. - a
Subjectelement with:- a
NameIDelement. - exactly one
SubjectConfirmationelement withMethodset tourn:oasis:names:tc:SAML:2.0:cm:bearer. - a
SubjectConfirmationDataelement withNotOnOrAfterset to a timestampthat occurs in the future and noNotBeforevalue.
- a
a
Conditionselement with:NotBeforeomitted or in the past.NotOnOrAfteromitted or in the future.An
Audiencethat is formatted as follows:https://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/WORKLOAD_PROVIDER_ID
Replace the following:
PROJECT_NUMBER: theproject numberof the Google Cloud project that you use to create workload identity pool.POOL_ID: an ID of your choice thatidentifies the workload identity pool. You must use the same IDwhen creating the workload identity pool later.WORKLOAD_PROVIDER_ID: an ID of yourchoice that identifies the workload identity pool provider. Youmust use the same ID when creating the workload identity poolprovider later.
at least one
AuthnStatementelement.a
SessionNotOnOrAfterelement with a timestamp that occurs in thefuture. Alternatively, omit the element.
For SAML assertions that are enclosed in a SAML response, the SAML responsemust contain:
- exactly one assertion that meets the SAML assertion criteria that isdescribed earlier in this section.
- an
IssueInstantattribute with a value less than 1 hour in the past. - the StatusCode
urn:oasis:names:tc:SAML:2.0:status:Success.
Either the SAML assertion, the response, or both must be signed.
Configure Workload Identity Federation
You only need to perform these steps once for each IdP. You can then usethe same workload identity pool and provider for multiple workloads and acrossmultiple Google Cloud projects.
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.
It's best touse 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.
Manage self-uploaded OIDC JWKs (Optional)
This section shows you how to manage self-uploaded OIDC JWKs in workloadidentity pool oidc providers.
Create a provider and upload OIDC JWKs
To create OIDC JWKs, seeJWT, JWS, JWE, JWK, and JWA Implementations.
To upload an OIDC JWK file when you create a workload identity pool provider,run thegcloud iam workload-identity-pools providers create-oidccommand with--jwk-json-path="JWK_JSON_PATH".ReplaceJWK_JSON_PATH with the path to the JWKs JSONfile.
This operation creates uploaded keys with the ones in thefile.
Update OIDC JWKs
To update OIDC JWKs, run thegcloud iam workload-identity-pools providers update-oidccommand with--jwk-json-path="JWK_JSON_PATH".ReplaceJWK_JSON_PATH with the path to theJWKs JSON file.
This operation replaces any existing uploaded keys with the ones in thefile. You cannot restore the replaced keys.
Delete all uploaded OIDC JWKs
To delete all of the uploaded OIDC JWKs and return to using the issuer URIto fetch the keys, run thegcloud iam workload-identity-pools providers update-oidccommand with--jwk-json-path="JWK_JSON_PATH".ReplaceJWK_JSON_PATH with the path to an empty file.Use the--issuer-uri flag to set the issuer URI.
This operation deletes all of your existing uploaded keys with the ones in thefile. You cannot restore the deleted keys.
Define an attribute mapping and condition
The OIDC tokens or SAML assertions issued by your IdP might contain multiple attributes,and you must decide which attribute you want to use as subject identifier(google.subject) in Google Cloud.
Optionally, you canmap additional attributes.You can then refer to these attributes when granting access to resources.
OIDC
Your attribute mappings can use the claims embedded in the ID token oraccess token issued by the external IdP.
You must map one of these claims togoogle.subject to uniquely identifythe user. To protect against spoofing threats, choose a claim with a uniquevalue that can't be changed.
Many IdPs populate thesub claim with a unique and immutableID. For these IdPs, consider mapping thesub claim togoogle.subject:
google.subject=assertion.sub
Avoid using a claim likeemail for this purpose. Email addressescan typically be reassigned or changed, so they don't uniquely and permanentlyidentify a user.
SAML
Your attribute mappings can use the<Subject> and<Attribute> elementsembedded in the assertion issued by the external IdP. SAMLattributes can be referred to using the following keywords:
assertion.subjectcontains theNameIDof theauthenticated user found in the<Subject>element.assertion.attributes['ATTRIBUTE_NAME']contains alist of values for the like-named<Attribute>.
You must map one of these claims togoogle.subject to uniquelyidentify the user. To protect against spoofing threats, choose a claim witha unique value that can't be changed.
Many IdPs populate theNameId with a unique andimmutable ID. For these IdPs, consider mapping theNameId attribute togoogle.subject:
google.subject=assertion.subject
Avoid using an attribute likehttp://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddressfor this purpose. Email addresses can typically be reassigned or changed, sothey don't uniquely and permanently identify a user.
Optionally, 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.
OIDC
You can use an attribute condition to restrict which userscan use Workload Identity Federation to obtain short-lived Google Cloudtokens.
For example, the following condition restricts access to tokens thatcontain a customservice_account claim with a valuetrue:
assertion.service_account==true
SAML
You can use an attribute condition to restrict which userscan use Workload Identity Federation to obtain short-lived Google Cloudtokens.
For example, the following condition restricts access to assertions thatcontain a customhttps://example.com/SAML/Attributes/AllowGcpFederationattribute with a valuetrue:
assertion.attributes['https://example.com/SAML/Attributes/AllowGcpFederation'][0]=='true'
Create the workload identity pool and provider
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) basic role alsoincludes 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.You now have collected all the information that you need to create a workload identitypool and provider:
Console
In the Google Cloud console, go to theNew workload provider and poolpage.
UnderCreate an identity pool, enter the following:
- Name: Name for the pool. The name is also used as the pool ID.You can't change the pool ID later.
- Description: Text that describes the purpose of the pool.
ClickContinue.
Configure provider settings as follows:
OIDC
- InSelect a provider, selectOpenID Connect (OIDC).
- InProvider name, enter a name for the provider. The name isalso used as the provider ID. You can't change the provider IDafter the provider is created.
- InIssuer URL, enter the issuer URL of your IdP. The URLmust start with
https:// - Optional: InJWK file (JSON), choose a JWK file to upload.If this field is not supplied, Google Cloud attempts tofetch a JWK from the issuer.
- Allowed audiences: Expected audience of ID tokens.
SAML
- InSelect a provider, selectSAML.
- InProvider name, enter a name for the provider. The name isalso used as the provider ID. You can't change the provider IDafter the provider is created.
- InIDP Metadata file (XML), upload the SAML metadata XMLdocument that is provided by your identity provider.
ClickContinue.
UnderConfigure provider attributes, addtheattribute mappings that you identifiedearlier in this guide.
UnderAttribute conditions, enter theattribute conditionthat you identified earlier in this guide. Leave the field blank if you don'thave an attribute condition.
To create the workload identity pool and provider, clickSave.
gcloud
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.
To add a workload identity pool provider, do the following:
OIDC
To add an OIDC workload identity pool provider, execute the followingcommand:
gcloud iam workload-identity-pools providers create-oidcWORKLOAD_PROVIDER_ID \ --location="global" \ --workload-identity-pool="POOL_ID" \ --issuer-uri="ISSUER" \ --allowed-audiences="AUDIENCE" \ --attribute-mapping="MAPPINGS" \ --attribute-condition="CONDITIONS" --jwk-json-path="JWK_JSON_PATH"
Replace the following:
WORKLOAD_PROVIDER_ID: A unique workloadidentity pool provider ID of your choice.POOL_ID: The workload identity pool IDthat you created earlier.ISSUER: An issuer URI as it is definedin the OIDC metadata.AUDIENCE: The expected audience of IDtokens, which, for many providers, matches the client ID.MAPPINGS: A comma-separated list ofattribute mappings that you createdearlier in this guide.CONDITIONS: An optionalattribute condition that you createdearlier in this guide. Remove the parameter ifyou don't have an attribute condition.JWK_JSON_PATH:An optional path to alocally uploaded OIDC JWKs.If this parameter isn't supplied, Google Cloud insteaduses your IdP's/.well-known/openid-configurationpath tosource the JWKs containing the public keys.
SAML
To add a SAML workload identity pool provider, execute the followingcommand:
gcloud iam workload-identity-pools providers create-samlWORKLOAD_PROVIDER_ID \ --location="global" \ --workload-identity-pool="POOL_ID" \ --idp-metadata-path="IDP_METADATA_PATH" \ --attribute-mapping="MAPPINGS" \ --attribute-condition="CONDITIONS"
Replace the following:
POOL_ID: the ID of the poolIDP_METADATA_PATH: the local pathto the SAML IdP's metadata documentMAPPINGS: a comma-separated list ofattribute mappingsthat you created earlier in this guideCONDITIONS: Optional: theattribute conditionthat you created earlier in this guide
The prefix
gcp-is reserved and can't be used in a workforce identity pool or workforce identity pool provider ID.Optional: Accept encrypted SAML assertions from your IdP
To enable your SAML 2.0 IdP to produce encrypted SAML assertions that can be accepted by workload identity federation, do the following:
- In workload identity federation, do the following:
- Create an asymmetric key pair for your workload identity pool provider.
- Download a certificate file that contains the public key.
- Configure your SAML IdP to use the public key to encrypt SAML assertions it issues.
- In your IdP, do the following:
- Enable assertion encryption, also known as token encryption.
- Upload the public key that you created in workload identity federation.
- Confirm that your IdP produces encrypted SAML assertions.
Create workload identity federation SAML assertion encryption keys
This section guides you through creating an asymmetric key pair that enables workload identity federation to accept encrypted SAML assertions.
Google Cloud uses the private key to decrypt the SAML assertions that your IdP issues. To create an asymmetric key pair for use with SAML encryption, run the following command. To learn more, seeSupported SAML encryption algorithms.
gcloudiamworkload-identity-poolsproviderskeyscreateKEY_ID\--workload-identity-poolWORKLOAD_POOL_ID\--providerWORKLOAD_PROVIDER_ID\--locationglobal\--useencryption\--specKEY_SPECIFICATION
Replace the following:
KEY_ID: a key name of your choiceWORKLOAD_POOL_ID: the pool IDWORKLOAD_PROVIDER_ID: the workforce identity pool provider IDKEY_SPECIFICATION: the key specification, which can be one ofrsa-2048,rsa-3072, andrsa-4096.
After the key pair is created, to download the public key into a certificate file, execute the following command. Only workload identity federation has access to the private key.
gcloudiamworkload-identity-poolsproviderskeysdescribeKEY_ID\--workload-identity-poolWORKLOAD_POOL_ID\--providerWORKLOAD_PROVIDER_ID\--locationglobal\--format"value(keyData.key)"\>CERTIFICATE_PATH
Replace the following:
KEY_ID: the key nameWORKLOAD_POOL_ID: the pool IDWORKLOAD_PROVIDER_ID: the workforce identity pool provider IDCERTIFICATE_PATH: the path to write the certificate to—for example,saml-certificate.cerorsaml-certificate.pem
Configure your SAML 2.0-compliant IdP to issue encrypted SAML assertions
Configure your SAML IdP to use the public certificate downloaded from the last step to encrypt the SAML assertions that it issues. Consult your IdP team for specific instructions.
After you configure your IdP to encrypt SAML assertions, we recommend that you check to make sure that the assertions it generates are actually encrypted. Even with SAML assertion encryption configured, workload identity federation can still process plaintext assertions.
Delete workload identity federation encryption keys
To delete SAML encryption keys run the following command:gcloudiamworkload-identity-poolsproviderskeysdeleteKEY_ID\--workload-identity-poolWORKLOAD_POOL_ID\--providerWORKLOAD_PROVIDER_ID\--locationglobal
Replace the following:
KEY_ID: the key nameWORKLOAD_POOL_ID: the pool IDWORKLOAD_PROVIDER_ID: the workforce identity pool provider ID
Supported SAML encryption algorithms
Workload identity federation supports the following key transport algorithms:
- http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p
- http://www.w3.org/2009/xmlenc11#rsa-oaep"
- http://www.w3.org/2001/04/xmlenc#rsa-1_5"
Workload identity federation supports the following block encryption algorithms:
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 a credential configuration
This section describes how to download the credential configuration using theGoogle Cloud console.
To let your workload access client libraries, you must first download and configureapplication default credentials (ADC) by doing the following:
In the Google Cloud console, go to theWorkload Identity Pools page.
Go to Workload Identity PoolsIn the table, select your pool to go the pool's detail page.
ClickGrant access.
SelectGrant access using federated identities (Recommended).
To download the Application Default Credential (ADC) so that your workload can access client libraries, do the following:
ClickDownload config.
In theConfigure your application dialog, do the following:
In theProvider drop-down list, select your provider.
InOIDC token path orSAML assertion path, enter the path where the token or assertion is located.
In theFormat type drop-down list, select the format.
ClickDownload configuration, and note the path where you saved the file.
Create a credential configuration
TheCloud Client Libraries, thegcloud CLI, and Terraform, can automatically obtain externalcredentials, and use these credentials to access Google Cloud. To letlibraries and tools complete this process, you have to provide a credentialconfiguration file. This file defines the following:
- Where to obtain external credentials from
- Which workload identity pool and provider to use
- Which service account to impersonate, if you use service accountimpersonation
The Cloud Client Libraries obtain external credentials from a local file, anHTTP URL, by running a local executable:
Executable-sourced credentials: The libraries launch an executablewhenever they need a new credential. If the executable succeeds in obtaininga new external credential, it must write a JSON document to
STDOUTthatlooks like the following:OIDC
{ "version": 1, "success": true, "token_type": "urn:ietf:params:oauth:token-type:id_token", "id_token": "HEADER.PAYLOAD.SIGNATURE", "expiration_time": 1620499962}If the executable fails to obtain a new credential, it must write a JSONdocument to
STDOUTthat looks like the following:{ "version": 1, "success": false, "code": "401", "message": "Caller not authorized."}The JSON documents use the following fields:
version: The version of the JSON output. Only version 1 is supported.success: The status of the response.When
true, the response must contain the fieldsid_tokenandtoken_type. The executable must exit with exit code 0.When
false, the response must contain the fieldscodeandmessageand exit with a non-zero value.token_type: The token type of the external credential. Supported values areurn:ietf:params:oauth:token-type:id_tokenurn:ietf:params:oauth:token-type:jwt
id_token: The external credential.expiration_time: The OIDC token expiration time in seconds (unix epoch time). This field is only required when an output file has been specified in the credential configuration.code: The error code string.message: The error message.
SAML
{ "version": 1, "success": true, "token_type": "urn:ietf:params:oauth:token-type:saml2", "saml_response": "...", "expiration_time": 1620499962}If the executable fails to obtain a new credential, it must write a JSONdocument to
STDOUTthat looks like the following:{ "version": 1, "success": false, "code": "401", "message": "Caller not authorized."}The JSON documents use the following fields:
version: The version of the JSON output. Only version 1 is supported.success: The status of the response.When
true, the response must contain the fieldsid_tokenandtoken_type. The executable must exit with exit code 0.When
false, the response must contain the fieldscodeandmessageand exit with a non-zero value.token_type: The token type of the external credential. Must beurn:ietf:params:oauth:token-type:saml2.saml_response: The SAML response or base64-encoded SAML assertion.expiration_time: The assertion expiration time in seconds (unix epoch time). This field is only required when an output file has been specified in the credential configuration.code: The error code string.message: The error message.
When launching the executable, client libraries set the followingenvironment variables:
GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE:Audience from the credential configuration. Always present.GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE:Expected subject token type. Always present.GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL:Service account email. Only present when service account impersonation is used.GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE:Output file location from the credential configuration. Only presentwhen specified in the credential configuration.
To use executable-sourced credentials, you must set the environmentvariable
GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLESto1.File-sourced credentials: The libraries read the external credentialfrom a local plain text or JSON file. For example:
JSON
{ "mytoken": "ey...}Text
ey...
The external credential can be:
- an OIDC token
- a SAML response
- a base64-encoded SAML assertion
You must periodically update the file so that it always contains a validcredential. For example, if the OIDC token or SAML assertion is valid forone hour, you must refresh the file at least once every hour.
URL-sourced credentials: The libraries perform a
GETrequest toan HTTP endpoint whenever they need a new credential. The endpoint mustreturn a plain text or JSON response that is equivalent to the format usedby file-sourced credentials.
To create a credential configuration file, do the following:
Executable-sourced credentials
gcloudiamworkload-identity-poolscreate-cred-config\projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/WORKLOAD_PROVIDER_ID\--service-account=SERVICE_ACCOUNT_EMAIL\--service-account-token-lifetime-seconds=SERVICE_ACCOUNT_TOKEN_LIFETIME\--sts-location=REGION\--output-file=FILEPATH.json\--executable-command=EXECUTABLE_COMMAND\--executable-timeout-millis=EXECUTABLE_TIMEOUT\--executable-output-file=EXECUTABLE_OUTPUT_FILE
Replace the following:
PROJECT_NUMBER: The project number of the project that contains the workload identity pool.POOL_ID: The ID of the workload identity pool.WORKLOAD_PROVIDER_ID: The ID of the workload identity pool provider.SERVICE_ACCOUNT_EMAIL: If you use service account impersonation, replace with the email address of the service account. Omit this flag if you don't use service account impersonation.SERVICE_ACCOUNT_TOKEN_LIFETIME: If you use service account impersonation, replace with the lifetime of the service account access token, in seconds; this defaults to one hour when not provided. Omit this flag if you don't use service account impersonation. To specify a lifetime longer than one hour, you must configure theconstraints/iam.allowServiceAccountCredentialLifetimeExtensionorganizational policy constraint.REGION: Optional. Specify the region of theregional Security Token Service endpoints, if they are available.FILEPATH: The file to save the configuration to.EXECUTABLE_COMMAND: The full command, including arguments, to run to retrieve the OIDC ID token—for example,--executable-command="/path/to/command --foo=bar".EXECUTABLE_TIMEOUT: The optional duration in milliseconds to wait for the executable to run (defaults to 30s).EXECUTABLE_OUTPUT_FILE: A path that points to the 3PI credentials generated by the executable. This is useful for caching the credentials. By specifying this path, the Auth libraries will first check for its existence before running the executable.
File-sourced credentials
gcloudiamworkload-identity-poolscreate-cred-config\projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/WORKLOAD_PROVIDER_ID\--service-account=SERVICE_ACCOUNT_EMAIL\--service-account-token-lifetime-seconds=SERVICE_ACCOUNT_TOKEN_LIFETIME\--sts-location=REGION\--output-file=FILEPATH.json\--credential-source-file=TOKEN_FILEPATH\--credential-source-type=SOURCE_TYPE\--credential-source-field-name=FIELD_NAME
Replace the following:
PROJECT_NUMBER: The project number of the project that contains the workload identity pool.POOL_ID: The ID of the workload identity pool.WORKLOAD_PROVIDER_ID: The ID of the workload identity pool provider.SERVICE_ACCOUNT_EMAIL: If you use service account impersonation, replace with the email address of the service account. Omit this flag if you don't use service account impersonation.SERVICE_ACCOUNT_TOKEN_LIFETIME: If you use service account impersonation, replace with the lifetime of the service account access token, in seconds; this defaults to one hour when not provided. Omit this flag if you don't use service account impersonation. To specify a lifetime longer than one hour, you must configure theconstraints/iam.allowServiceAccountCredentialLifetimeExtensionorganizational policy constraint.REGION: Optional. Specify the region of theregional Security Token Service endpoints, if they are available.FILEPATH: The file to save the configuration to.TOKEN_FILEPATH: The path where OIDC ID tokens are stored.SOURCE_TYPE: The format of the OIDC ID token file, set totext(default) orjson.FIELD_NAME: The field in the text file that contains the token (ifSOURCE_TYPEisjson).
URL-sourced credentials
gcloudiamworkload-identity-poolscreate-cred-config\projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/WORKLOAD_PROVIDER_ID\--service-account=SERVICE_ACCOUNT_EMAIL\--service-account-token-lifetime-seconds=SERVICE_ACCOUNT_TOKEN_LIFETIME\--sts-location=REGION\--output-file=FILEPATH.json\--credential-source-url="TOKEN_URL"\--credential-source-headers="KEY_1=VALUE_1,KEY_2=VALUE_2"\--credential-source-type=SOURCE_TYPE\--credential-source-field-name=FIELD_NAME
Replace the following:
PROJECT_NUMBER: Project number of the project that contains the workload identity pool.POOL_ID: ID of the workload identity pool.WORKLOAD_PROVIDER_ID: ID of the workload identity pool providerSERVICE_ACCOUNT_EMAIL: If you use service account impersonation, replace with the mail address of the service account. Omit this flag if you don't use service account impersonation.SERVICE_ACCOUNT_TOKEN_LIFETIME: If you use service account impersonation, replace with the lifetime of the service account access token, in seconds; this defaults to one hour when not provided. Omit this flag if you don't use service account impersonation. To specify a lifetime longer than one hour, you must configure theconstraints/iam.allowServiceAccountCredentialLifetimeExtensionorganizational policy constraint.REGION: Optional. Specify the region of theregional Security Token Service endpoints, if they are available.FILEPATH: File to save the configuration to.TOKEN_URL: URL to retrieve OIDC ID token fromKEY_n,VALUE_n: Custom headers to include in HTTP request toTOKEN_URLSOURCE_TYPE: Format of the OIDC ID token file, set totext(default) orjsonFIELD_NAME: Field in the text file that contains the token (ifSOURCE_TYPEisjson)
Use the credential configuration to access Google Cloud
To let tools and client libraries use your credential configuration, do thefollowing:
Initialize an environment variable
GOOGLE_APPLICATION_CREDENTIALSand pointit to the credential configuration file:Bash
whereexport GOOGLE_APPLICATION_CREDENTIALS=`pwd`/FILEPATH.json
FILEPATHis the relative path to the credential configuration file.PowerShell
where$env:GOOGLE_APPLICATION_CREDENTIALS = Resolve-Path 'FILEPATH.json'
FILEPATHis the relative path to the credential configuration file.Use a client library or tool that supports Workload Identity Federation and canfind credentials automatically:
C++
TheGoogle Cloud Client Libraries for C++support Workload Identity Federation since versionv2.6.0.To use Workload Identity Federation, you must build the client librarieswith version 1.36.0 or later of gRPC.
Go
Client libraries for Go support Workload Identity Federation if they use versionv0.0.0-20210218202405-ba52d332ba99 or later of the
golang.org/x/oauth2module.To check which version of this module your client library uses, run thefollowing commands:
cd$GOPATH/src/cloud.google.com/gogolist-mgolang.org/x/oauth2Java
Client libraries for Java support Workload Identity Federation if they use version 0.24.0or later of the
com.google.auth:google-auth-library-oauth2-httpartifact.To check which version of this artifact your client library uses, run thefollowing Maven command in your application directory:
mvndependency:list-DincludeArtifactIds=google-auth-library-oauth2-httpNode.js
Client libraries for Node.js support Workload Identity Federation if they use version7.0.2 or later of the
google-auth-librarypackage.To check which version of this package your client library uses, run thefollowing command in your application directory:
npmlistgoogle-auth-libraryWhen you create a
GoogleAuthobject, you can specify a project ID, or you canallowGoogleAuthto find the project ID automatically. To find the project IDautomatically, the service account in the configuration file must have theBrowser role (roles/browser), or a role with equivalent permissions, on yourproject. For details, see theREADMEfor thegoogle-auth-librarypackage.Python
Client libraries for Python support Workload Identity Federation if they use version1.27.0 or later of the
google-authpackage.To 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.gcloud
To authenticate using Workload Identity Federation, use the
gcloud auth logincommand:gcloud auth login --cred-file=FILEPATH.json
Replace
FILEPATHwith the path to thecredential configuration file.Support for Workload Identity Federation in gcloud CLI is available inversion 363.0.0 and later versions of the gcloud CLI.
Terraform
TheGoogle Cloud providersupports Workload Identity Federation if you use version 3.61.0 or later:
terraform { required_providers { google = { source = "hashicorp/google" version = "~> 3.61.0" } }}bq
To authenticate using Workload Identity Federation, use the
gcloud auth logincommand, as follows:gcloud auth login --cred-file=FILEPATH.json
Replace
FILEPATHwith the path to thecredential configuration file.Support for Workload Identity Federation in bq is available inversion 390.0.0 and later versions of the gcloud CLI.
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.