Package com.google.auth.oauth2 (1.6.0)

Classes

AccessToken

Represents a temporary OAuth2 access token and its expiration information.

AwsCredentials

AWS credentials representing a third-party identity for calling Google APIs.

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

AwsCredentials.Builder

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

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

ExternalAccountCredentials

Base external account credentials class.

Handles initializing external credentials, calls to STS, and service account impersonation.

ExternalAccountCredentials.Builder

Base builder for external account credentials.

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

IdentityPoolCredentials

Url-sourced and file-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

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

UserCredentials

OAuth2 Credentials representing a user's identity and consent.

UserCredentials.Builder

Interfaces

IdTokenProvider

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

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.

QuotaProjectIdProvider

Interface for GoogleCredentials that return a quota project ID.

TokenStore

Interface for long term storage of tokens

Enums

IdTokenProvider.Option

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

ComputeEngineCredentials

  • FORMAT_FULL
  • LICENSES_TRUE


ImpersonatedCredential

  • INCLUDE_EMAIL

Exceptions

TokenVerifier.VerificationException

Custom exception for wrapping all verification errors.