Configure Workload Identity Federation with other identity providers

This guide describes how to use Workload Identity Federation with otheridentity providers (IdPs).

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 withhttps://. 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-path to 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:

  • The signing certificate must meet the following validity requirements:

    • notBefore: a timestamp that is no more than 7 days in the future
    • notAfter: 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 theRS256 orES256 algorithm.
  • Tokens contain anaud claim 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 anexp claim that is in the future and aniat claimthat is in the past.

    The value ofexp must be greater than the value ofiat by 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 anISSUER claim so that theURLISSUER/.well-known/openid-configuration pointsto the IdP's OIDC metadata endpoint.

  • To upload local JWK keys, seeManage OIDC JWKs.

Note: Workload Identity Federation doesn't support opaque tokens ortoken introspection.

SAML

Configure your IdP so that SAML assertions contain elements that meet thefollowing criteria:

  • anIssuer element 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.
  • aSubject element with:
    • aNameID element.
    • exactly oneSubjectConfirmation element withMethod set tourn:oasis:names:tc:SAML:2.0:cm:bearer.
    • aSubjectConfirmationData element withNotOnOrAfter set to a timestampthat occurs in the future and noNotBefore value.
  • aConditions element with:

    • NotBefore omitted or in the past.
    • NotOnOrAfter omitted or in the future.
    • AnAudience that 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 oneAuthnStatement element.

  • aSessionNotOnOrAfter element 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.
  • anIssueInstant attribute with a value less than 1 hour in the past.
  • the StatusCodeurn: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:

  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. It's best touse 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

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.subject contains theNameID of 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:

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

  1. In the Google Cloud console, go to theNew workload provider and poolpage.

    Go to New workload provider and pool

  2. 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.
  3. ClickContinue.

  4. 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 withhttps://
    • 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.
  5. ClickContinue.

  6. UnderConfigure provider attributes, addtheattribute mappings that you identifiedearlier in this guide.

  7. UnderAttribute conditions, enter theattribute conditionthat you identified earlier in this guide. Leave the field blank if you don'thave an attribute condition.

  8. To create the workload identity pool and provider, clickSave.

gcloud

  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.
  2. 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-configuration path 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 pool
    • IDP_METADATA_PATH: the local pathto the SAML IdP's metadata document
    • MAPPINGS: a comma-separated list ofattribute mappingsthat you created earlier in this guide
    • CONDITIONS: Optional: theattribute conditionthat you created earlier in this guide

    The prefixgcp- 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.
    Note that, even with SAML encryption provider keys configured, workload identity federation can still process a plaintext assertion.

    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 choice
    • WORKLOAD_POOL_ID: the pool ID
    • WORKLOAD_PROVIDER_ID: the workforce identity pool provider ID
    • KEY_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 name
    • WORKLOAD_POOL_ID: the pool ID
    • WORKLOAD_PROVIDER_ID: the workforce identity pool provider ID
    • CERTIFICATE_PATH: the path to write the certificate to—for example,saml-certificate.cer orsaml-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 name
    • WORKLOAD_POOL_ID: the pool ID
    • WORKLOAD_PROVIDER_ID: the workforce identity pool provider ID

    Supported SAML encryption algorithms

    Workload identity federation supports the following key transport algorithms:

    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.

  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 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:

  1. In the Google Cloud console, go to theWorkload Identity Pools page.

    Go to Workload Identity Pools
  2. In the table, select your pool to go the pool's detail page.

  3. ClickGrant access.

  4. SelectGrant access using federated identities (Recommended).

  5. To download the Application Default Credential (ADC) so that your workload can access client libraries, do the following:

    1. ClickDownload config.

    2. In theConfigure your application dialog, do the following:

      1. In theProvider drop-down list, select your provider.

      2. InOIDC token path orSAML assertion path, enter the path where the token or assertion is located.

      3. In theFormat type drop-down list, select the format.

    3. 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 toSTDOUT thatlooks 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 toSTDOUT that 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.

      Whentrue, the response must contain the fieldsid_token andtoken_type. The executable must exit with exit code 0.

      Whenfalse, the response must contain the fieldscode andmessage and exit with a non-zero value.

    • token_type: The token type of the external credential. Supported values are

      • urn:ietf:params:oauth:token-type:id_token
      • urn: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 toSTDOUT that 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.

      Whentrue, the response must contain the fieldsid_token andtoken_type. The executable must exit with exit code 0.

      Whenfalse, the response must contain the fieldscode andmessage and 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 environmentvariableGOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES to1.

  • 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 aGET request 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.

Note: Unlike aservice account key,a credential configuration file doesn't contain a private key and doesn't needto be kept confidential. Details about the credential configuration file areavailable athttps://google.aip.dev/auth/4117.

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_TYPE isjson).

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 provider
  • SERVICE_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 from
  • KEY_n,VALUE_n: Custom headers to include in HTTP request toTOKEN_URL
  • SOURCE_TYPE: Format of the OIDC ID token file, set totext (default) orjson
  • FIELD_NAME: Field in the text file that contains the token (ifSOURCE_TYPE isjson)

Use the credential configuration to access Google Cloud

To let tools and client libraries use your credential configuration, do thefollowing:

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

    Bash

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

    PowerShell

      $env:GOOGLE_APPLICATION_CREDENTIALS = Resolve-Path 'FILEPATH.json'
    whereFILEPATH is the relative path to the credential configuration file.
  2. 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 thegolang.org/x/oauth2 module.

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

    cd$GOPATH/src/cloud.google.com/gogolist-mgolang.org/x/oauth2

    Java

    Client libraries for Java support Workload Identity Federation if they use version 0.24.0or later of thecom.google.auth:google-auth-library-oauth2-http artifact.

    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-http

    Node.js

    Client libraries for Node.js support Workload Identity Federation if they use version7.0.2 or later of thegoogle-auth-library package.

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

    npmlistgoogle-auth-library

    When you create aGoogleAuth object, you can specify a project ID, or you canallowGoogleAuth to 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 theREADME for thegoogle-auth-library package.

    Python

    Client libraries for Python support Workload Identity Federation if they use version1.27.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.

    gcloud

    To authenticate using Workload Identity Federation, use thegcloud auth login command:

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

    ReplaceFILEPATH with 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 thegcloud auth login command, as follows:

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

    ReplaceFILEPATH with 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

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.