Package com.google.auth.oauth2 (1.27.0)

Classes

AccessToken

Represents a temporary OAuth2 access token and its expiration information.

AccessToken.Builder

AwsCredentialSource

The AWS credential source. Stores data required to retrieve the AWS credential.

AwsCredentials

Credentials representing an AWS third-party identity for calling Google APIs. AWS security credentials are either sourced by calling EC2 metadata endpoints, environment variables, or a user provided supplier method.

By default, attempts to exchange the external credential for a GCP access token.

AwsCredentials.Builder

AwsSecurityCredentials

Defines AWS security credentials. These are either retrieved from the AWS security_credentials endpoint or AWS environment variables.

ClientId

An OAuth2 user authorization Client ID and associated information.

Corresponds to the information in the json file downloadable for a Client ID.

ClientId.Builder

CloudShellCredentials

OAuth2 credentials representing the built-in service account for Google Cloud Shell.

CloudShellCredentials.Builder

ComputeEngineCredentials

OAuth2 credentials representing the built-in service account for a Google Compute Engine VM.

Fetches access tokens from the Google Compute Engine metadata server.

These credentials use the IAM API to sign data. See #sign(byte[]) for more details.

ComputeEngineCredentials.Builder

CredentialAccessBoundary

Defines an upper bound of permissions available for a GCP credential via AccessBoundaryRules.

See for more information.

CredentialAccessBoundary.AccessBoundaryRule

Defines an upper bound of permissions on a particular resource.

The following snippet shows an AccessBoundaryRule that applies to the Cloud Storage bucket bucket-one to set the upper bound of permissions to those defined by the roles/storage.objectViewer role.


 AccessBoundaryRule rule = AccessBoundaryRule.newBuilder()
   .setAvailableResource("//storage.googleapis.com/projects/_/buckets/bucket-one")
   .addAvailablePermission("inRole:roles/storage.objectViewer")
   .build();
 

CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition

An optional condition that can be used as part of a AccessBoundaryRule to further restrict permissions.

For example, you can define an AvailabilityCondition that applies to a set of Cloud Storage objects whose names start with auth:


 AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder()
   .setExpression("resource.name.startsWith('projects/_/buckets/bucket-123/objects/auth')")
   .build();
 

CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition.Builder

CredentialAccessBoundary.AccessBoundaryRule.Builder

CredentialAccessBoundary.Builder

DefaultPKCEProvider

Implements PKCE using only the Java standard library. See https://www.rfc-editor.org/rfc/rfc7636.

https://developers.google.com/identity/protocols/oauth2/native-app#step1-code-verifier.

DownscopedCredentials

DownscopedCredentials enables the ability to downscope, or restrict, the Identity and Access Management (IAM) permissions that a short-lived credential can use for Cloud Storage.

To downscope permissions you must define a CredentialAccessBoundary which specifies the upper bound of permissions that the credential can access. You must also provide a source credential which will be used to acquire the downscoped credential.

See for more information.

Usage:


 GoogleCredentials sourceCredentials = GoogleCredentials.getApplicationDefault()
    .createScoped("https://www.googleapis.com/auth/cloud-platform");

 CredentialAccessBoundary.AccessBoundaryRule rule =
     CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
         .setAvailableResource(
             "//storage.googleapis.com/projects/_/buckets/bucket")
         .addAvailablePermission("inRole:roles/storage.objectViewer")
         .build();

 DownscopedCredentials downscopedCredentials =
     DownscopedCredentials.newBuilder()
         .setSourceCredential(sourceCredentials)
         .setCredentialAccessBoundary(
             CredentialAccessBoundary.newBuilder().addRule(rule).build())
         .build();

 AccessToken accessToken = downscopedCredentials.refreshAccessToken();

 OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);

 Storage storage =
 StorageOptions.newBuilder().setCredentials(credentials).build().getService();

 Blob blob = storage.get(BlobId.of("bucket", "object"));
 System.out.printf("Blob %s retrieved.", blob.getBlobId());
 

Note that OAuth2CredentialsWithRefresh can instead be used to consume the downscoped token, allowing for automatic token refreshes by providing a OAuth2CredentialsWithRefresh.OAuth2RefreshHandler.

DownscopedCredentials.Builder

ExternalAccountAuthorizedUserCredentials

OAuth2 credentials sourced using external identities through Workforce Identity Federation.

Obtaining the initial access and refresh token can be done through the Google Cloud CLI.

Example credentials file: { "type": "external_account_authorized_user", "audience": "//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID", "refresh_token": "refreshToken", "token_url": "https://sts.googleapis.com/v1/oauthtoken", "token_info_url": "https://sts.googleapis.com/v1/introspect", "client_id": "clientId", "client_secret": "clientSecret" }

ExternalAccountAuthorizedUserCredentials.Builder

Builder for ExternalAccountAuthorizedUserCredentials.

ExternalAccountCredentials

Base external account credentials class.

Handles initializing external credentials, calls to the Security Token Service, and service account impersonation.

ExternalAccountCredentials.Builder

Base builder for external account credentials.

ExternalAccountSupplierContext

Context object to pass relevant variables from external account credentials to suppliers. This will be passed on any call made to IdentityPoolSubjectTokenSupplier or AwsSecurityCredentialsSupplier.

GdchCredentials

GdchCredentials.Builder

GoogleAuthUtils

This public class provides shared utilities for common OAuth2 utils or ADC. It also exposes convenience methods such as a getter for well-known Application Default Credentials file path

GoogleCredentials

Base type for credentials for authorizing calls to Google APIs using OAuth2.

GoogleCredentials.Builder

IdToken

Represents a temporary IdToken and its JsonWebSignature object

IdTokenCredentials

IdTokenCredentials provides a Google Issued OpenIdConnect token.
Use an ID token to access services that require presenting an ID token for authentication such as Cloud Functions or Cloud Run.
The following Credential subclasses support IDTokens: ServiceAccountCredentials, ComputeEngineCredentials, ImpersonatedCredentials.

For more information see
Usage:

String credPath = "/path/to/svc_account.json"; String targetAudience = "https://example.com";

// For Application Default Credentials (as ServiceAccountCredentials) // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/svc.json GoogleCredentials adcCreds = GoogleCredentials.getApplicationDefault(); if (!adcCreds instanceof IdTokenProvider) { // handle error message }

IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder() .setIdTokenProvider(adcCreds) .setTargetAudience(targetAudience).build();

// for ServiceAccountCredentials ServiceAccountCredentials saCreds = ServiceAccountCredentials.fromStream(new FileInputStream(credPath)); saCreds = (ServiceAccountCredentials) saCreds.createScoped(Arrays.asList("https://www.googleapis.com/auth/iam")); IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder() .setIdTokenProvider(saCreds) .setTargetAudience(targetAudience).build();

// for ComputeEngineCredentials ComputeEngineCredentials caCreds = ComputeEngineCredentials.create(); IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder() .setIdTokenProvider(caCreds) .setTargetAudience(targetAudience) .setOptions(Arrays.asList(ComputeEngineCredentials.ID_TOKEN_FORMAT_FULL)) .build();

// for ImpersonatedCredentials ImpersonatedCredentials imCreds = ImpersonatedCredentials.create(saCreds, "impersonated-account@project.iam.gserviceaccount.com", null, Arrays.asList("https://www.googleapis.com/auth/cloud-platform"), 300); IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder() .setIdTokenProvider(imCreds) .setTargetAudience(targetAudience) .setOptions(Arrays.asList(ImpersonatedCredentials.INCLUDE_EMAIL)) .build();

// Use the IdTokenCredential in an authorized transport GenericUrl genericUrl = new GenericUrl("https://example.com"); HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(tokenCredential); HttpTransport transport = new NetHttpTransport(); HttpRequest request = transport.createRequestFactory(adapter).buildGetRequest(genericUrl); HttpResponse response = request.execute();

// Print the token, expiration and the audience System.out.println(tokenCredential.getIdToken().getTokenValue()); System.out.println(tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudienceAsList()); System.out.println(tokenCredential.getIdToken().getJsonWebSignature().getPayload().getExpirationTimeSeconds());

IdTokenCredentials.Builder

IdentityPoolCredentialSource

The IdentityPool credential source. Dictates the retrieval method of the external credential, which can either be through a metadata server or a local file.

IdentityPoolCredentials

Url-sourced, file-sourced, or user provided supplier method-sourced external account credentials.

By default, attempts to exchange the external credential for a GCP access token.

IdentityPoolCredentials.Builder

ImpersonatedCredentials

ImpersonatedCredentials allowing credentials issued to a user or service account to impersonate another. The source project using ImpersonatedCredentials must enable the "IAMCredentials" API. Also, the target service account must grant the originating principal the "Service Account Token Creator" IAM role.

Usage:

String credPath = "/path/to/svc_account.json"; ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials .fromStream(new FileInputStream(credPath)); sourceCredentials = (ServiceAccountCredentials) sourceCredentials .createScoped(Arrays.asList("https://www.googleapis.com/auth/iam"));

ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create(sourceCredentials, "impersonated-account@project.iam.gserviceaccount.com", null, Arrays.asList("https://www.googleapis.com/auth/devstorage.read_only"), 300);

Storage storage_service = StorageOptions.newBuilder().setProjectId("project-id") .setCredentials(targetCredentials).build().getService();

for (Bucket b : storage_service.list().iterateAll()) System.out.println(b);

ImpersonatedCredentials.Builder

JwtClaims

Value class representing the set of fields used as the payload of a JWT token.

To create and customize claims, use the builder:


 Claims claims = Claims.newBuilder()
     .setAudience("https://example.com/some-audience")
     .setIssuer("some-issuer@example.com")
     .setSubject("some-subject@example.com")
     .build();
 

JwtClaims.Builder

JwtCredentials

Credentials class for calling Google APIs using a JWT with custom claims.

Uses a JSON Web Token (JWT) directly in the request metadata to provide authorization.


 JwtClaims claims = JwtClaims.newBuilder()
     .setAudience("https://example.com/some-audience")
     .setIssuer("some-issuer@example.com")
     .setSubject("some-subject@example.com")
     .build();
 Credentials = JwtCredentials.newBuilder()
     .setPrivateKey(privateKey)
     .setPrivateKeyId("private-key-id")
     .setJwtClaims(claims)
     .build();
 

JwtCredentials.Builder

MemoryTokensStorage

Represents an in-memory storage of tokens.

OAuth2Credentials

Base type for Credentials using OAuth2.

OAuth2Credentials.Builder

OAuth2CredentialsWithRefresh

A refreshable alternative to OAuth2Credentials.

To enable automatic token refreshes, you must provide an OAuth2RefreshHandler.

OAuth2CredentialsWithRefresh.Builder

PluggableAuthCredentialSource

Encapsulates the credential source portion of the configuration for PluggableAuthCredentials.

Command is the only required field. If timeout_millis is not specified, the library will default to a 30 second timeout.

Sample credential source for Pluggable Auth credentials: { ... "credential_source": { "executable": { "command": "/path/to/get/credentials.sh --arg1=value1 --arg2=value2", "timeout_millis": 5000, "output_file": "/path/to/generated/cached/credentials" } } }

PluggableAuthCredentials

PluggableAuthCredentials enables the exchange of workload identity pool external credentials for Google access tokens by retrieving 3rd party tokens through a user supplied executable. These scripts/executables are completely independent of the Google Cloud Auth libraries. These credentials plug into ADC and will call the specified executable to retrieve the 3rd party token to be exchanged for a Google access token.

To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable must be set to '1'. This is for security reasons.

Both OIDC and SAML are supported. The executable must adhere to a specific response format defined below.

The executable must print out the 3rd party token to STDOUT in JSON format. When an output_file is specified in the credential configuration, the executable must also handle writing the JSON response to this file.

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

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

Error response sample: { "version": 1, "success": false, "code": "401", "message": "Error message." }

The expiration_time field in the JSON response is only required for successful responses when an output file was specified in the credential configuration.

The auth libraries will populate certain environment variables that will be accessible by the executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE, GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.

Please see this repositories README for a complete executable request/response specification.

PluggableAuthCredentials.Builder

ServiceAccountCredentials

OAuth2 credentials representing a Service Account for calling Google APIs.

By default uses a JSON Web Token (JWT) to fetch access tokens.

ServiceAccountCredentials.Builder

ServiceAccountJwtAccessCredentials

Service Account credentials for calling Google APIs using a JWT directly for access.

Uses a JSON Web Token (JWT) directly in the request metadata to provide authorization.

ServiceAccountJwtAccessCredentials.Builder

TokenVerifier

Handle verification of Google-signed JWT tokens.

TokenVerifier.Builder

UserAuthorizer

Handles an interactive 3-Legged-OAuth2 (3LO) user consent authorization.

UserAuthorizer.Builder

UserAuthorizer.TokenResponseWithConfig

Represents the response from an OAuth token exchange, including configuration details used to initiate the flow.

This response can be used to initialize the following credentials types:


 // UserCredentials when Google is the identity provider:
 UserCredentials userCredentials = UserCredentials.newBuilder()
     .setHttpTransportFactory(tokenResponseWithConfig.getHttpTransportFactory())
     .setClientId(tokenResponseWithConfig.getClientId())
     .setClientSecret(tokenResponseWithConfig.getClientSecret())
     .setAccessToken(tokenResponseWithConfig.getAccessToken())
     .setRefreshToken(tokenResponseWithConfig.getRefreshToken())
     .setTokenServerUri(tokenResponseWithConfig.getTokenServerUri())
     .build();

 // ExternalAccountAuthorizedUserCredentials when using Workforce Identity Federation:
 ExternalAccountAuthorizedUserCredentials externalAccountAuthorizedUserCredentials =
     ExternalAccountAuthorizedUserCredentials.newBuilder()
         .setHttpTransportFactory(tokenResponseWithConfig.getHttpTransportFactory())
         .setClientId(tokenResponseWithConfig.getClientId())
         .setClientSecret(tokenResponseWithConfig.getClientSecret())
         .setAccessToken(tokenResponseWithConfig.getAccessToken())
         .setRefreshToken(tokenResponseWithConfig.getRefreshToken())
         .setTokenUrl(tokenResponseWithConfig.getTokenServerUri().toURL().toString())
         .build();
 

UserCredentials

OAuth2 Credentials representing a user's identity and consent.

UserCredentials.Builder

Interfaces

AwsSecurityCredentialsSupplier

Supplier for retrieving AWS Security credentials for AwsCredentials to exchange for GCP access tokens.

IdTokenProvider

Interface for an Google OIDC token provider. This type represents a google issued OIDC token.

IdentityPoolSubjectTokenSupplier

JwtProvider

Interface for creating custom JWT tokens

OAuth2Credentials.CredentialsChangedListener

Listener for changes to credentials.

This is called when token content changes, such as when the access token is refreshed. This is typically used by code caching the access token.

OAuth2CredentialsWithRefresh.OAuth2RefreshHandler

Interface for the refresh handler.

PKCEProvider

QuotaProjectIdProvider

Interface for GoogleCredentials that return a quota project ID.

TokenStore

Interface for long term storage of tokens

Enums

ExternalAccountCredentials.SubjectTokenTypes

Enum specifying values for the subjectTokenType field in ExternalAccountCredentials.

IdTokenProvider.Option

Enum of various credential-specific options to apply to the token.

ComputeEngineCredentials

  • FORMAT_FULL
  • LICENSES_TRUE


ImpersonatedCredential

  • INCLUDE_EMAIL

UserAuthorizer.ClientAuthenticationType

Represents the client authentication types as specified in RFC 7591.

For more details, see RFC 7591.

Exceptions

TokenVerifier.VerificationException

Custom exception for wrapping all verification errors.