Get started with Google Auth Library

Google Auth Library is an open source authentication client library for Java.This document describes how to use this library to authenticate your Javaapplications to access Google Cloud services.

By following this guide, you will learn how to:

  • Add the necessary Auth Library dependencies to your project using Maven,Gradle, or Simple Build Tool (SBT).
  • Authenticate using various methods, with a focus on Application DefaultCredentials (ADC).
  • Configure advanced authentication scenarios, including Workload IdentityFederation, Workforce Identity Federation, and service account impersonation.
  • Generate and use downscoped tokens to limit permissions.
  • Integrate credentials with Google HTTP client libraries.

This documentation is intended for Java developers. For complete API details,refer to theGoogle Auth Library API Documentation.

The Google Auth Library for Java consists of four artifacts:

  • google-auth-library-credentials contains base classes andinterfaces for Google credentials.
  • google-auth-library-appengine contains App Enginecredentials and depends on the App Engine SDK.
  • google-auth-library-oauth2-http contains a variety ofcredentials and utility methods, including capabilities to get ApplicationDefault Credentials. It also provides the server-side approach for generatingdownscoped tokens.
  • google-auth-library-cab-token-generator provides theclient-side approach for generating downscoped tokens.

Validate credential configurations

When you use credential configurations, such as JSON, file paths, or streams,from an external source, you must validate them. Providing unvalidatedcredentials to Google APIs or client libraries for authentication toGoogle Cloud can compromise the security of your systemsand data.

For more information, seeExternally sourcedcredentials.Default Credentials.

Import the Auth Library

To import the Auth Library, usecom.google.cloud:libraries-bom or usethe Google Auth Library Bill of Materials with Maven or Gradle.

Java SDK libraries-bom

To authenticate to a client library in the Java SDK(for example,google-cloud-datastore) using the Auth Library, uselibraries-bom, which will pull in the versions of Auth Library compatiblewith that client library.

For example, to import the Auth Library with Maven using apom.xml:

<dependencyManagement><dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>libraries-bom</artifactId><version>26.53.0</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>

If you don't uselibraries-bom or other client libraries, import the Auth modules directly with theGoogle Auth Library Bill of Materials.

Google Auth Library Bill of Materials

You can use the Google Auth Library Bill of Materials to ensure that the Authmodules and relevant transitive dependencies are compatible.

Maven

Add the following to yourpom.xml file:

<dependencyManagement><dependencies><dependency><groupId>com.google.auth</groupId><artifactId>google-auth-library-bom</artifactId><version>1.30.1</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>

In the<dependencies> section, you can specify any of the Auth modules thatare needed. For example, to include thegoogle-auth-library-oauth2-httpmodule, add the following<dependency> item:

<dependency><groupId>com.google.auth</groupId><!--LettheBOMmanagethemoduleanddependencyversions--><!--Replacewiththemodule(s)thatareneeded--><artifactId>google-auth-library-oauth2-http</artifactId></dependency>

Replacegoogle-auth-library-oauth2-http in the example withgoogle-auth-library-credentials orgoogle-auth-library-appengine, depending on your application needs.

Gradle

Similar to Maven, Gradle users can use thegoogle-auth-library-bom tomanage dependency versions and ensure compatibility between the differentgoogle-auth-library modules.

To use the BOM with Gradle, add the BOM as aplatform dependency. Then, addthegoogle-auth-library modules that you need. The BOM ensures that theversions of all the modules you use are compatible. For example, add thefollowing to yourbuild.gradle file:

dependencies{// The BOM will manage the module versions and transitive dependenciesimplementationplatform('com.google.auth:google-auth-library-bom:1.30.1')// Replace with the module(s) that are neededimplementation'com.google.auth:google-auth-library-oauth2-http'}

Scala

Unlike Maven and Gradle, SBT (Scala Build Tool) does not support Maven Bills ofMaterials (BOMs). As a result, when using Scala, you cannot import thegoogle-auth-library-bom to automatically handle compatible versions of theAuth Library modules and their transitive dependencies.

Instead, you'll need to add each required submodule directly to yourbuild.sbt file. It's critical to explicitly specify and align the versions ofallgoogle-auth-library modules you are using. Failing to keep the versionsconsistent can lead to version conflicts among transitive dependencies,potentially causing unexpected behavior or runtime errors in your application.

Add this to your dependencies if using SBT:

// Replace this with the implementation module that suits your needslibraryDependencies+="com.google.auth"%"google-auth-library-oauth2-http"%"1.30.1"

Migrate fromGoogleCredential toGoogleCredentials

GoogleCredentialfromgoogle-api-java-client is deprecated andGoogleCredentials is therecommended replacement.

InstantiateGoogleCredentials usingApplication Default Credentials (ADC).This is the recommended approach:

GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault();

The way you useGoogleCredentials depends on the client library:

Application Default Credentials

The Google Auth Library provides an implementation ofApplication Default Credentials (ADC)for Java. ADC provide a way to get authorization credentials to call Google APIs.

Use ADC when your application requires a consistent identity and authorizationlevel, independent of the user. We recommend using ADC to authorize calls toCloud APIs, especially when building applications on Google Cloud.

ADC also supportsWorkload Identity Federation,enabling applications to access Google Cloud resources from externalplatforms like Amazon Web Services (AWS), Microsoft Azure, or any identityprovider that supports OpenID Connect (OIDC). We recommend workload identityfederation for non-Google Cloud environments because it eliminates theneed to download, manage, and store service account private keys locally.

Get Application Default Credentials

To get Application Default Credentials, useGoogleCredentials.getApplicationDefault()orGoogleCredentials.getApplicationDefault(HttpTransportFactory). Thesemethods return Application Default Credentials to identify and authorize thewhole application.

The following are searched, in this order, to find the Application DefaultCredentials:

  1. Credentials file pointed to by theGOOGLE_APPLICATION_CREDENTIALSenvironment variable.
  2. Credentials provided by the Google Cloud SDKgcloud auth application-default login command.
  3. Google App Engine built-in credentials.
  4. Google Cloud Shell built-in credentials.
  5. Google Compute Engine built-in credentials.
    • Skip this check by setting the environment variableNO_GCE_CHECK=true.
    • Customize the metadata server address by setting the environmentvariableGCE_METADATA_HOST=<hostname>.

Explicit credential loading

To get credentials from a Service Account JSON key, useGoogleCredentials.fromStream(InputStream) orGoogleCredentials.fromStream(InputStream, HttpTransportFactory) as shown in thefollowing example code.

The credentials must be refreshed before the access token isavailable.

GoogleCredentialscredentials=GoogleCredentials.fromStream(newFileInputStream("/path/to/credentials.json"));credentials.refreshIfExpired();AccessTokentoken=credentials.getAccessToken();// ORAccessTokentoken=credentials.refreshAccessToken();

Impersonated credentials

UseImpersonatedCredentials to allow a credential (the principal) toimpersonate a service account (the target). This lets the principal accessresources as the target, without needing the target's private key.

To useImpersonatedCredentials, you must meet the following requirements:

  • The principal's project must have theIAMCredentials API enabled.
  • The principal must have theService Account Token Creator (Identity and Access Management)role on the target service account.

The following code sample createsImpersonatedCredentials. The principal'scredential is obtained from Application Default Credentials (ADC). The resultingImpersonatedCredentials are then used to access Google Cloud Storage asthe target service account.

// The principal (ADC) has the Service Account Token Creator role on the target service account.GoogleCredentialssourceCredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList("https://www.googleapis.com/auth/iam"));ImpersonatedCredentialscredentials=ImpersonatedCredentials.newBuilder().setSourceCredentials(sourceCredentials).setTargetPrincipal("impersonated-account@project.iam.gserviceaccount.com").setScopes(Arrays.asList("https://www.googleapis.com/auth/devstorage.read_only")).build();Storagestorage=StorageOptions.newBuilder().setProjectId("project-id").setCredentials(credentials).build().getService();for(Bucketb:storage.list().iterateAll()){System.out.println(b);}

Workload Identity Federation

Workload Identity Federation lets your application access Google Cloudresources from Amazon Web Services (AWS), Microsoft Azure, or any identityprovider that supports OpenID Connect (OIDC).

Conventionally, applications running outside Google Cloud have used serviceaccount keys to access Google Cloud resources. Using identity federation,your workload can impersonate a service account. This lets the externalworkload access Google Cloud resources directly, eliminating themaintenance and security burden associated with service account keys.

Access resources from AWS

To access Google Cloud resources from Amazon Web Services (AWS), you mustfirst configure workload identity federation. The setup process is detailed inAccessing resources from AWS.

As part of that process, you will generate a credential configuration file.This file contains non-sensitive metadata that instructs the library how toretrieve external subject tokens and exchange them for service account accesstokens. You can generate the file using theGoogle Cloud CLI:

# Generate an AWS configuration file.gcloudiamworkload-identity-poolscreate-cred-config\projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>POOL_ID</var>/providers/<var>AWS_PROVIDER_ID</var>\--service-account<var>SERVICE_ACCOUNT_EMAIL</var>\--aws\--output-file/path/to/generated/config.json

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • POOL_ID: the workload identity pool ID.
  • AWS_PROVIDER_ID: the AWS provider ID.
  • SERVICE_ACCOUNT_EMAIL: the email of the service account to impersonate.

The example generates the configuration file in the specified outputfile.

If you are usingAWS IMDSv2, you need to add an additional flag--enable-imdsv2 to thegcloud iam workload-identity-pools create-cred-config command:

gcloudiamworkload-identity-poolscreate-cred-config\projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/AWS_PROVIDER_ID\--service-accountSERVICE_ACCOUNT_EMAIL\--aws\--output-file/path/to/generated/config.json\--enable-imdsv2

You can nowuse the Auth library to callGoogle Cloud resources from AWS.

Access resources from Microsoft Azure

To access Google Cloud resources from Microsoft Azure, you must firstconfigure workload identity federation. The setup process is detailed inAccessing resources from Azure.

As part of that process, you will generate a credential configuration file.This file contains non-sensitive metadata that instructs the library how toretrieve external subject tokens and exchange them for service account accesstokens. You can generate the file using theGoogle Cloud CLI:

# Generate an Azure configuration file.gcloudiamworkload-identity-poolscreate-cred-config\projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>POOL_ID</var>/providers/<var>AZURE_PROVIDER_ID</var>\--service-account<var>SERVICE_ACCOUNT_EMAIL</var>\--azure\--output-file/path/to/generated/config.json

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • POOL_ID: the workload identity pool ID.
  • AZURE_PROVIDER_ID: the Azure provider ID.
  • SERVICE_ACCOUNT_EMAIL: the email of the service account to impersonate.

This command generates the configuration file in the specified output file.

You can nowuse the Auth library to call Google Cloudresources from Azure.

Access resources from an OIDC identity provider

To access Google Cloud resources from an identity provider that supportsOpenID Connect (OIDC), you must first configureworkload identity federation as detailed inConfiguring workload identity federation from an OIDC identity provider.

As part of that process, you will generate a credential configuration file usingtheGoogle Cloud CLI. This file containsnon-sensitive metadata that instructs the library how to retrieve externalsubject tokens and exchange them for service account access tokens.

For OIDC providers, the Auth library can retrieve OIDC tokens from a local file(file-sourced credentials), a local server(URL-sourced credentials), or a X.509certificate and private-key combination (X.509 certificate-sourced credentials).

File-sourced credentials

For file-sourced credentials, a background process must continuouslyrefresh the file location with a new OIDC token prior to expiration.For tokens with one hour lifetimes, you need to update the token in the fileevery hour. You can store the token directly as plain text or in JSON format.

To generate a file-sourced OIDC configuration, run the following command:

# Generate an OIDC configuration file for file-sourced credentials.gcloudiamworkload-identity-poolscreate-cred-config\projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>POOL_ID</var>/providers/<var>OIDC_PROVIDER_ID</var>\--service-account<var>SERVICE_ACCOUNT_EMAIL</var>\--credential-source-file<var>PATH_TO_OIDC_ID_TOKEN</var>\# Optional arguments for file types. Default is "text":# --credential-source-type "json" \# Optional argument for the field that contains the OIDC credential.# This is required for json.# --credential-source-field-name "id_token" \--output-file/path/to/generated/config.json

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • POOL_ID: the workload identity pool ID.
  • OIDC_PROVIDER_ID: the OIDC provider ID.
  • SERVICE_ACCOUNT_EMAIL: the email of the service account to impersonate.
  • PATH_TO_OIDC_ID_TOKEN: the path used to retrieve the OIDC token.

This command generates the configuration file in the specified output file.

URL-sourced credentials

For URL-sourced credentials, a local server must host a GET endpoint thatprovides an OIDC token in plain text or JSON format. You can specifyadditional HTTP headers to send in the token request, if required by theendpoint.

To generate a URL-sourced OIDC workload identity configuration, run thefollowing command:

# Generate an OIDC configuration file for URL-sourced credentials.gcloudiamworkload-identity-poolscreate-cred-config\projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>POOL_ID</var>/providers/<var>OIDC_PROVIDER_ID</var>\--service-account<var>SERVICE_ACCOUNT_EMAIL</var>\--credential-source-url<var>URL_TO_GET_OIDC_TOKEN</var>\--credential-source-headers<var>HEADER_KEY=HEADER_VALUE</var>\# Optional arguments for file types. Default is "text":# --credential-source-type "json" \# Optional argument for the field that contains the OIDC credential.# This is required for json.# --credential-source-field-name "id_token" \--output-file/path/to/generated/config.json

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • POOL_ID: the workload identity pool ID.
  • OIDC_PROVIDER_ID: the OIDC provider ID.
  • SERVICE_ACCOUNT_EMAIL: the email of the service account to impersonate.
  • URL_TO_GET_OIDC_TOKEN: the URL of the local server endpoint to call toretrieve the OIDC token.
  • HEADER_KEY andHEADER_VALUE: the additional header key and value pairs topass along the GET request toURL_TO_GET_OIDC_TOKEN, for exampleMetadata-Flavor=Google.

You can nowuse the Auth library to callGoogle Cloud resources from an OIDC provider.

Access resources using X.509 certificate-sourced credentials

For X.509 certificate-sourced credentials, the authentication library uses anX.509 certificate and private key to prove your application's identity. X.509certificates include an expiration date and must be renewed before they expireto maintain access.

For more information, see theofficial documentation.

Generate configuration files for X.509 federation

To configure X.509 certificate-sourced credentials, you generate two separatefiles: a primary credential configuration file and a certificate configurationfile.

  • The primary credential configuration file contains the necessary metadata forauthentication. This file also references the certificate configuration file.
  • The certificate configuration file specifies the file paths for the X.509certificate, private key, and trust chain.

Thegcloud iam workload-identity-pools create-cred-configcommand can be used to create both.

The location wheregcloud creates the certificate configuration file depends onwhether you use the--credential-cert-configuration-output-file flag.

Default behavior (recommended)

If you omit the--credential-cert-configuration-output-file flag,gcloudcreates the certificate configuration file at a default, well-known locationthat the Auth library can automatically discover. This approach is suitablefor most use cases. The default credential configuration file is namedconfig.json and the default certificate configuration file is namedcertificate_config.json.

For example, run the following command to create the configuration files usingthe default behavior:

gcloudiamworkload-identity-poolscreate-cred-config\projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>POOL_ID</var>/providers/<var>PROVIDER_ID</var>\--service-account<var>SERVICE_ACCOUNT_EMAIL</var>\--credential-cert-path"<var>PATH_TO_CERTIFICATE</var>"\--credential-cert-private-key-path"<var>PATH_TO_PRIVATE_KEY</var>"\--credential-cert-trust-chain-path"<var>PATH_TO_TRUST_CHAIN</var>"\--output-file/path/to/config.json

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • POOL_ID: the workload identity pool ID.
  • PROVIDER_ID: the provider ID.
  • SERVICE_ACCOUNT_EMAIL: the email of the service account to impersonate.
  • PATH_TO_CERTIFICATE: the path where your leaf X.509 certificate islocated.
  • PATH_TO_PRIVATE_KEY: the path where the corresponding private key forthe leaf certificate is located.
  • PATH_TO_TRUST_CHAIN: the path of the X.509 certificate trust chainfile. This file should be a PEM-formatted file containing any intermediatecertificates required to complete the trust chain between the leaf certificateand the trust store configured in the Workload Identity Federation pool. Theleaf certificate is optional in this file.

This command results in the following:

  • /path/to/config.json: Created at the path you specified. This file willcontain"use_default_certificate_config": true to instruct clients to lookfor the certificate configuration at the default path.
  • certificate_config.json: Created at the default Google Cloud CLIconfiguration path, which is typically~/.config/gcloud/certificate_config.json on Linux and macOS, or%APPDATA%\gcloud\certificate_config.json on Windows.

Custom location behavior

If you need to store the certificate configuration file in a non-defaultlocation, use the--credential-cert-configuration-output-file flag.

Example command (custom location):

gcloudiamworkload-identity-poolscreate-cred-config\projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>POOL_ID</var>/providers/<var>PROVIDER_ID</var>\--service-account<var>SERVICE_ACCOUNT_EMAIL</var>\--credential-cert-path"<var>PATH_TO_CERTIFICATE</var>"\--credential-cert-private-key-path"<var>PATH_TO_PRIVATE_KEY</var>"\--credential-cert-trust-chain-path"<var>PATH_TO_TRUST_CHAIN</var>"\--credential-cert-configuration-output-file"/custom/path/cert_config.json"\--output-file/path/to/config.json

This command results in:

  • /path/to/config.json: created at the path you specified. This file willcontain a"certificate_config_location" field that points to your custom path.
  • cert_config.json: created at/custom/path/cert_config.json, as specifiedby the flag.

You can nowuse the Auth library to callGoogle Cloud resources with X.509 certificate-sourced credentials.

Use executable-sourced credentials with OIDC and SAML

For executable-sourced credentials, a local executable is used to retrieve thethird-party token. The executable must provide a valid, unexpired OIDC IDtoken or SAML assertion in JSON format tostdout.

To use executable-sourced credentials, theGOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLESenvironment variable must be set to1.

To generate an executable-sourced workload identity configuration, run thefollowing command:

# Generate a configuration file for executable-sourced credentials.gcloudiamworkload-identity-poolscreate-cred-config\projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>POOL_ID</var>/providers/<var>PROVIDER_ID</var>\--service-account=<var>SERVICE_ACCOUNT_EMAIL</var>\--subject-token-type=<var>SUBJECT_TOKEN_TYPE</var>\# The absolute path for the program, including arguments.# e.g. --executable-command="/path/to/command --foo=bar"--executable-command=<var>EXECUTABLE_COMMAND</var>\# Optional argument for the executable timeout. Defaults to 30s.# --executable-timeout-millis=<var>EXECUTABLE_TIMEOUT</var> \# Optional argument for the absolute path to the executable output file.# See below on how this argument impacts the library behaviour.# --executable-output-file=<var>EXECUTABLE_OUTPUT_FILE</var> \--output-file/path/to/generated/config.json

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • POOL_ID: the workload identity pool ID.
  • PROVIDER_ID: the OIDC or SAML provider ID.
  • SERVICE_ACCOUNT_EMAIL: the email of the service account to impersonate.
  • SUBJECT_TOKEN_TYPE: the subject token type.
  • EXECUTABLE_COMMAND: the full command to run, including arguments.Must be an absolute path to the program.

The--executable-timeout-millis flag is optional; it specifies the duration(in milliseconds) for which the Auth library will wait for the executable tofinish. If not provided, it defaults to 30 seconds. The maximum allowed valueis two minutes, and the minimum is five seconds.

The optional--executable-output-file flag specifies a path to cache theexecutable's third-party credential response. Caching helps improve performancebecause the auth libraries first check this file for valid, unexpiredcredentials before running the executable. If valid, cached credentials exist,the libraries use them, avoiding unnecessary executable runs.

Your executable must write the credential response to this file. The authlibraries only read from this location. The file's content must match theexpected JSON format.

To retrieve the third-party token, the library will run the executableusing the command specified. The executable's output must adhere to the responseformat specified in the following examples, and it must output the response tostdout.

Here's a sample successful executable OIDC response:

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

And here's a sample successful executable SAML response:

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

When you specify an output file using the--executable-output-file argumentin the credential configuration, successful executable responses must includeanexpiration_time field. This allows the Auth Library to effectively cacheand manage the validity of the credentials stored in that file.

Here's a sample executable error response:

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

These are all required fields for an error response. The library uses the codeand message fields as part of a thrown exception.

Response format fields summary:*version: The version of the JSON output. Only version 1 is supported.*success: When true, the response must include the 3rd party token and token type. The response must also include theexpiration_time field if an output file was specified in the credential configuration. The executable must also exit with an exit code of 0. When false, the response must include the error code and message fields and exit with a non-zero value.*token_type: This field specifies the 3rd party subject token type. It must beurn:ietf:params:oauth:token-type:jwt,urn:ietf:params:oauth:token-type:id_token, orurn:ietf:params:oauth:token-type:saml2.*id_token: The 3rd party OIDC token.*saml_response: The 3rd party SAML response.*expiration_time: The 3rd party subject token expiration time in seconds (Unix epoch time).*code: The error code string.*message: The error message.

All response types must include both theversion andsuccess fields. * Successful responses must include thetoken_type and one ofid_token orsaml_response. Theexpiration_time field must also be present if an output file was specified in the credential configuration. * Error responses must include both thecode andmessage fields.

The library populates the following environment variables when it runs theexecutable:

  • GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE: the audience field from the credentialconfiguration. Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE: this expected subject token type.Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL: The service accountemail address. Only present when service account impersonation is used.
  • GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE: The output file location from thecredential configuration. Only present when specified in the credentialconfiguration.

These environment variables can be used by the executable to avoid hard-codingthese values.

Security considerations

The following security practices are recommended:

  • Prevent rogue processes from running theexecutable because it will output sensitive credentials to those processesand their users viastdout.
  • Prevent rogue processes from altering the configuration orthe executable's invocation.

Because of the complexity of using executable-sourced credentials, we stronglyrecommend that you use other supported mechanisms, such as file or URL sources,for providing third-party credentials unless they don't meet your specificrequirements.

You can nowuse the Auth library to callGoogle Cloud resources from an OIDC or SAML provider.

Use a custom supplier with OIDC and SAML

A custom implementation ofIdentityPoolSubjectTokenSupplier can be used whilebuildingIdentityPoolCredentials to supply a subject token that can beexchanged for a Google Cloud access token. The supplier must return avalid, unexpired subject token when called by the Google Cloudcredential.

IdentityPoolCredentials don't cache the returned token, so implement cachinglogic in the token supplier to prevent multiple requests forthe same subject token.

importjava.io.IOException;publicclassCustomTokenSupplierimplementsIdentityPoolSubjectTokenSupplier{@OverridepublicStringgetSubjectToken(ExternalAccountSupplierContextcontext)throwsIOException{// Any call to the supplier passes a context object with the requested// audience and subject token type.stringaudience=context.getAudience();stringtokenType=context.getSubjectTokenType();try{// Return a valid, unexpired token for the requested audience and token type.// Note that IdentityPoolCredentials don't cache the subject token so// any caching logic needs to be implemented in the token supplier.returnretrieveToken(audience,tokenType);}catch(Exceptione){// If token is unavailable, throw IOException.thrownewIOException(e);}}privateStringretrieveToken(stringtokenType,stringaudience){// Retrieve a subject token of the requested type for the requested audience.}}
CustomTokenSuppliertokenSupplier=newCustomTokenSupplier();IdentityPoolCredentialsidentityPoolCredentials=IdentityPoolCredentials.newBuilder().setSubjectTokenSupplier(tokenSupplier)// Sets the token supplier..setAudience(...)// Sets the Google Cloud audience..setSubjectTokenType(SubjectTokenTypes.JWT)// Sets the subject token type..build();

Where theaudience is:

//iam.googleapis.com/projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>WORKLOAD_POOL_ID</var>/providers/<var>PROVIDER_ID</var>

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • WORKLOAD_POOL_ID: the workload identity pool ID.
  • PROVIDER_ID: the provider ID.

You can also find the values for audience, service account impersonation URL,and any other builder field by generating acredential configuration file with the gcloud CLI.

Use a custom supplier with AWS

A custom implementation ofAwsSecurityCredentialsSupplier can be provided wheninitializingAwsCredentials. If provided, theAwsCredentials instance willdefer to the supplier to retrieve AWS security credentials to exchange for aGoogle Cloud access token. The supplier must return valid, unexpired AWSsecurity credentials when called by the Google Cloud credential.

AwsCredentials don't cache the returned AWS security credentials or region, soimplement caching logic in the supplier to prevent multiple requests for thesame resources.

classCustomAwsSupplierimplementsAwsSecurityCredentialsSupplier{@OverrideAwsSecurityCredentialsgetAwsSecurityCredentials(ExternalAccountSupplierContextcontext)throwsIOException{// Any call to the supplier passes a context object with the requested// audience.Stringaudience=context.getAudience();try{// Return valid, unexpired AWS security credentials for the requested audience.// Note that AwsCredentials don't cache the AWS security credentials so// any caching logic needs to be implemented in the credentials' supplier.returnretrieveAwsSecurityCredentials(audience);}catch(Exceptione){// If credentials are unavailable, throw IOException.thrownewIOException(e);}}@OverrideStringgetRegion(ExternalAccountSupplierContextcontext)throwsIOException{try{// Return a valid AWS region. i.e. "us-east-2".// Note that AwsCredentials don't cache the region so// any caching logic needs to be implemented in the credentials' supplier.returnretrieveAwsRegion();}catch(Exceptione){// If region is unavailable, throw IOException.thrownewIOException(e);}}privateAwsSecurityCredentialsretrieveAwsSecurityCredentials(stringaudience){// Retrieve Aws security credentials for the requested audience.}privateStringretrieveAwsRegion(){// Retrieve current AWS region.}}
CustomAwsSupplierawsSupplier=newCustomAwsSupplier();AwsCredentialscredentials=AwsCredentials.newBuilder().setSubjectTokenType(SubjectTokenTypes.AWS4)// Sets the subject token type..setAudience(...)// Sets the Google Cloud audience..setAwsSecurityCredentialsSupplier(supplier)// Sets the supplier..build();

Where theaudience is://iam.googleapis.com/projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>WORKLOAD_POOL_ID</var>/providers/<var>PROVIDER_ID</var>

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • WORKLOAD_POOL_ID: the workload identity pool ID.
  • PROVIDER_ID: the provider ID.

You can also find the values for audience, service account impersonation URL,and any other builder field by generating acredential configuration file with the gcloud CLI.

Configurable token lifetime

When you create a credential configuration with workload identity federationusing service account impersonation, you can provide an optional argument toconfigure the service account access token lifetime.

To generate the configuration with configurable token lifetime, run thefollowing command (this example uses an AWS configuration, but the tokenlifetime can be configured for all workload identity federation providers):

# Generate an AWS configuration file with configurable token lifetime.gcloudiamworkload-identity-poolscreate-cred-config\projects/<var>PROJECT_NUMBER</var>/locations/global/workloadIdentityPools/<var>POOL_ID</var>/providers/<var>AWS_PROVIDER_ID</var>\--service-account<var>SERVICE_ACCOUNT_EMAIL</var>\--aws\--output-file/path/to/generated/config.json\--service-account-token-lifetime-seconds<var>TOKEN_LIFETIME</var>

Replace the following:

  • PROJECT_NUMBER: the Google Cloud project number.
  • POOL_ID: the workload identity pool ID.
  • AWS_PROVIDER_ID: the AWS provider ID.
  • SERVICE_ACCOUNT_EMAIL: the email of the service account to impersonate.
  • TOKEN_LIFETIME: the selected lifetime duration of the service account accesstoken in seconds.

Theservice-account-token-lifetime-seconds flag is optional. If not provided,the flag defaults to one hour.The minimum allowed value is 600 (10 minutes) and the maximum allowed value is43200 (12 hours).If you require a lifetime greater than one hour, you must add the serviceaccount as an allowed value in an Organization Policy Service that enforces theconstraints/iam.allowServiceAccountCredentialLifetimeExtension constraint.

Configuring a short lifetime (for example, 10 minutes) causes the library toinitiate the entire token exchange flow every 10 minutes. This calls the 3rdparty token provider even if the 3rd party token is not expired.

Use external account authorized user workforce credentials

External account authorized user credentialslet you to sign in with a web browser to an external identity provider accountusing the gcloud CLI and create a configuration for the authlibrary to use.

To generate an external account authorized user workforce identityconfiguration, run the following command:

gcloudauthapplication-defaultlogin--login-config=LOGIN_CONFIG

Where the following variable needs to be substituted:

This opens a browser flow for you to sign in using the configured third-partyidentity provider. It then stores the external account authorized userconfiguration at the well-known ADC location.

The Auth library will then use the provided refresh token from the configurationto generate and refresh an access token to call Google Cloud services.

The default lifetime of the refresh token is one hour. After this, you need togenerate a new configuration from the gcloud CLI. You can modify thelifetime by changing thesession duration of the workforce pool,and you can set it as high as 12 hours.

Use external identities

You can use external identities withApplication Default Credentials. To useexternal identities with Application Default Credentials, generate the JSONcredentials configuration file for your external identity as described in theWorkload Identity Federation section.Once generated, store the path to this file in theGOOGLE_APPLICATION_CREDENTIALS environment variable.

exportGOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json

The library can now choose the right type of client and initialize credentialsfrom the context that the configuration file provides.

GoogleCredentialsgoogleCredentials=GoogleCredentials.getApplicationDefault();StringprojectId="your-project-id";Stringurl="https://storage.googleapis.com/storage/v1/b?project="+projectId;HttpCredentialsAdaptercredentialsAdapter=newHttpCredentialsAdapter(googleCredentials);HttpRequestFactoryrequestFactory=newNetHttpTransport().createRequestFactory(credentialsAdapter);HttpRequestrequest=requestFactory.buildGetRequest(newGenericUrl(url));JsonObjectParserparser=newJsonObjectParser(GsonFactory.getDefaultInstance());request.setParser(parser);HttpResponseresponse=request.execute();System.out.println(response.parseAsString());

You can also explicitly initialize external account clients using the generatedconfiguration file.

ExternalAccountCredentialscredentials=ExternalAccountCredentials.fromStream(newFileInputStream("/path/to/credentials.json"));

Security considerations

This library does not perform any validation on thetoken_url,token_info_url,orservice_account_impersonation_url fields of the credential configuration.We don't recommend that you use a credential configuration that you did notgenerate with the gcloud CLI unless you verify that the URL fieldspoint to a googleapis.com domain.

Downscope with Credential Access Boundaries

Downscoping with Credential Access Boundariesenables restricting the Identity and Access Management (IAM) permissions that ashort-lived credential can use for Cloud Storage. This involves creating aCredentialAccessBoundary that defines the restrictions that apply to thedownscoped token. Using downscoped credentials ensures that tokens in flight alwayshave the least privileges. SeePrinciple of Least Privilege.

Create aCredentialAccessBoundary

The Credential Access Boundary specifies which resources the newly createdcredential can access. It also specifies an upper bound on the permissionsthat are available on each resource. It includes one or moreAccessBoundaryRule objects.

The following snippet shows how to initialize aCredentialAccessBoundarywith oneAccessBoundaryRule. This rule specifies that the downscoped tokenwill have read-only access to objects starting withcustomer-a in bucketbucket-123.

// Create the AccessBoundaryRule.StringavailableResource="//storage.googleapis.com/projects/_/buckets/bucket-123";StringavailablePermission="inRole:roles/storage.objectViewer";Stringexpression="resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')";CredentialAccessBoundary.AccessBoundaryRulerule=CredentialAccessBoundary.AccessBoundaryRule.newBuilder().setAvailableResource(availableResource).addAvailablePermission(availablePermission).setAvailabilityCondition(CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition.newBuilder().setExpression(expression).build()).build();// Create the CredentialAccessBoundary with the rule.CredentialAccessBoundarycredentialAccessBoundary=CredentialAccessBoundary.newBuilder().addRule(rule).build();

Common usage pattern

The common usage pattern involves a token broker with elevated access. Thisbroker generates downscoped credentials from higher access source credentials.It then passes the downscoped short-lived access tokens to a token consumerthrough a secure authenticated channel for limited access to Google CloudStorage resources.

Generate downscoped tokens

There are two ways to generate downscoped tokens using aCredentialAccessBoundary:

  • Server-side (usingDownscopedCredentials): the client calls theSecurity Token Service (STS) each time a downscoped token is needed. This is suitable forapplications where Credential Access Boundary rules change infrequently orwhere you reuse a single downscoped credential many times. A key considerationis that every rule change requires you to make a new call to the STS. Thisapproach is available within thegoogle-auth-library-oauth2-http library anddoes not require any additional dependencies. This makes it simpler tointegrate. It is a good choice if your use case doesn't demand the specificbenefits of the client-side approach.

  • Client-side (usingClientSideCredentialAccessBoundaryFactory): theclient retrieves cryptographic material once and then generates multiple downscoped tokens locally. This minimizes calls to the STS and is more efficientwhen Credential Access Boundary rules change frequently, because the clientdoesn't need to contact the STS for each rule change. This is also moreefficient for applications that need to generate many unique downscoped tokens.This approach is available in thegoogle-auth-library-cab-token-generatormodule. However, this module comes with its own set of dependencies. Thesedependencies can add complexity to your project. Consider this approach ifminimizing STS calls and generating numerous unique tokens are primary concerns.You will also need to manage the additional dependencies.

Server-side CAB

TheDownscopedCredentials class can be used to produce a downscoped accesstoken from a source credential and theCredentialAccessBoundary.

// Retrieve the source credentials from ADC.GoogleCredentialssourceCredentials=GoogleCredentials.getApplicationDefault().createScoped("https://www.googleapis.com/auth/cloud-platform");// Create an Access Boundary Rule which will restrict the downscoped token to having read-only// access to objects starting with "customer-a" in bucket "bucket-123".StringavailableResource="//storage.googleapis.com/projects/_/buckets/bucket-123";StringavailablePermission="inRole:roles/storage.objectViewer";Stringexpression="resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')";CredentialAccessBoundary.AccessBoundaryRulerule=CredentialAccessBoundary.AccessBoundaryRule.newBuilder().setAvailableResource(availableResource).addAvailablePermission(availablePermission).setAvailabilityCondition(newAvailabilityCondition(expression,/* title= */null,/* description= */null)).build();// Initialize the DownscopedCredentials class.DownscopedCredentialsdownscopedCredentials=DownscopedCredentials.newBuilder().setSourceCredential(sourceCredentials).setCredentialAccessBoundary(CredentialAccessBoundary.newBuilder().addRule(rule).build()).build();// Retrieve the downscoped access token.// You will need to pass this to the Token Consumer.AccessTokendownscopedAccessToken=downscopedCredentials.refreshAccessToken();

Client-side CAB

For client-side CAB, theClientSideCredentialAccessBoundaryFactory is usedwith a source credential. After initializing the factory, thegenerateToken()method can be called repeatedly with differentCredentialAccessBoundaryobjects to create multiple downscoped tokens.

// Retrieve the source credentials from ADC.GoogleCredentialssourceCredentials=GoogleCredentials.getApplicationDefault().createScoped("https://www.googleapis.com/auth/cloud-platform");// Create an Access Boundary Rule which will restrict the downscoped token to having read-only// access to objects starting with "customer-a" in bucket "bucket-123".StringavailableResource="//storage.googleapis.com/projects/_/buckets/bucket-123";StringavailablePermission="inRole:roles/storage.objectViewer";Stringexpression="resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')";CredentialAccessBoundary.AccessBoundaryRulerule=CredentialAccessBoundary.AccessBoundaryRule.newBuilder().setAvailableResource(availableResource).addAvailablePermission(availablePermission).setAvailabilityCondition(newAvailabilityCondition(expression,/* title= */null,/* description= */null)).build();// Initialize the ClientSideCredentialAccessBoundaryFactory.ClientSideCredentialAccessBoundaryFactoryfactory=ClientSideCredentialAccessBoundaryFactory.newBuilder().setSourceCredential(sourceCredentials).build();// Create the CredentialAccessBoundary with the rule.CredentialAccessBoundarycredentialAccessBoundary=CredentialAccessBoundary.newBuilder().addRule(rule).build();// Generate the downscoped access token.// You will need to pass this to the Token Consumer.AccessTokendownscopedAccessToken=factory.generateToken(credentialAccessBoundary);

Use downscoped access tokens

You can set up a token broker on a server in a private network. Variousworkloads (token consumers) in the same network send authenticated requests tothat broker for downscoped tokens. These tokens allow them to access or modifyspecific Google Cloud Storage buckets.

The broker instantiates downscoped credentials instances that can generateshort-lived downscoped access tokens. It then passes these tokens to the tokenconsumer.

These downscoped access tokens can be used by the Token Consumer usingOAuth2Credentials orOAuth2CredentialsWithRefresh. You can then use thiscredential to initialize a storage client instance to access Google CloudStorage resources with restricted access.

// You can pass an `OAuth2RefreshHandler` to `OAuth2CredentialsWithRefresh` that will allow the// library to seamlessly handle downscoped token refreshes on expiration.OAuth2CredentialsWithRefresh.OAuth2RefreshHandlerhandler=newOAuth2CredentialsWithRefresh.OAuth2RefreshHandler(){@OverridepublicAccessTokenrefreshAccessToken(){// Retrieve the token from your Token Broker.returnaccessToken;}};// The downscoped token is retrieved from the token broker.AccessTokendownscopedToken=handler.refreshAccessToken();// Build the OAuth2CredentialsWithRefresh from the downscoped token and pass a refresh handler// to handle token expiration. Passing the original downscoped token or the expiry here is optional,// because the refresh_handler will generate the downscoped token on demand.OAuth2CredentialsWithRefreshcredentials=OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(downscopedToken).setRefreshHandler(handler).build();// Use the credentials with the Cloud Storage SDK.StorageOptionsoptions=StorageOptions.newBuilder().setCredentials(credentials).build();Storagestorage=options.getService();// Call Cloud Storage APIs.// Because we passed the downscoped credential, we will have limited read-only access to objects// starting with "customer-a" in bucket "bucket-123".storage.get(...)

Only Cloud Storage supports Credential Access Boundaries; otherGoogle Cloud services don't support this feature.

Use credentials withgoogle-http-client

Credentials provided bycom.google.auth:google-auth-library-oauth2-httpcan be used with Google's HTTP-based clients. Google's HTTP-based clientsprovide anHttpCredentialsAdapter which can be used as anHttpRequestInitializer, the last argument for their builders.

importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.services.bigquery.Bigquery;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault();HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);Bigquerybq=newBigquery.Builder(HTTP_TRANSPORT,JSON_FACTORY,requestInitializer).setApplicationName(APPLICATION_NAME).build();

Verify JWT Tokens (Beta feature)

To verify a JWT token, use theTokenVerifier class.

Verify a signature

To verify a signature, use the defaultTokenVerifier:

importcom.google.api.client.json.webtoken.JsonWebSignature;importcom.google.auth.oauth2.TokenVerifier;TokenVerifiertokenVerifier=TokenVerifier.newBuilder().build();try{JsonWebSignaturejsonWebSignature=tokenVerifier.verify(tokenString);// Optionally, verify additional claims.if(!"expected-value".equals(jsonWebSignature.getPayload().get("additional-claim"))){// Handle custom verification error.}}catch(TokenVerifier.VerificationExceptione){// The token is invalid.}

Customize theTokenVerifier

To customize aTokenVerifier, instantiate it using its builder:

importcom.google.api.client.json.webtoken.JsonWebSignature;importcom.google.auth.oauth2.TokenVerifier;TokenVerifiertokenVerifier=TokenVerifier.newBuilder().setAudience("audience-to-verify").setIssuer("issuer-to-verify").build();try{JsonWebSignaturejsonWebSignature=tokenVerifier.verify(tokenString);// Optionally, verify additional claims.if(!"expected-value".equals(jsonWebSignature.getPayload().get("additional-claim"))){// Handle custom verification error.}}catch(TokenVerifier.VerificationExceptione){// The token is invalid.}

For more options, see theTokenVerifier.Builder documentation.

google-auth-library-credentials

This artifact contains base classes and interfaces for Google credentials:

  • Credentials: this is the base class for an authorized identity.Implementations of this class can authorize your application.
  • RequestMetadataCallback: this is the interface for the callback thatreceives the result of the asynchronousCredentials.getRequestMetadata(URI, Executor, RequestMetadataCallback).
  • ServiceAccountSigner: this is the interface for a service account signer.Implementations of this class are capable of signing byte arrays using thecredentials associated to a Google Service Account.

google-auth-library-appengine

This artifact depends on the App Engine SDK (appengine-api-1.0-sdk).Use it only for applications running on App Engine environments thatuseurlfetch. TheAppEngineCredentials class lets you authorize yourApp Engine application given an instance ofAppIdentityService.

Usage:

importcom.google.appengine.api.appidentity.AppIdentityService;importcom.google.appengine.api.appidentity.AppIdentityServiceFactory;importcom.google.auth.Credentials;importcom.google.auth.appengine.AppEngineCredentials;AppIdentityServiceappIdentityService=AppIdentityServiceFactory.getAppIdentityService();Credentialscredentials=AppEngineCredentials.newBuilder().setScopes(...).setAppIdentityService(appIdentityService).build();
Important:com.google.auth.appengine.AppEngineCredentials is a separateclass fromcom.google.auth.oauth2.AppEngineCredentials.

google-auth-library-cab-token-generator

This module provides theClientSideCredentialAccessBoundaryFactory class,enabling client-side generation of downscoped tokens for Cloud Storageusing Credential Access Boundaries. This approach is particularly useful forapplications requiring frequent changes to Credential Access Boundary rules orthe generation of many unique downscoped tokens, because it minimizes calls tothe Security Token Service (STS). For usage examples, see theClient-side CAB section. This module comes with its own setof dependencies. Evaluate whether the benefits of client-side downscopingoutweigh the added complexity for your specific use case.

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 2026-02-19 UTC.