Represents a temporary OAuth2 access token and its expiration information.
AccessToken.Builder AwsCredentialSourceThe AWS credential source. Stores data required to retrieve the AWS credential.
AwsCredentialsCredentials 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 AwsSecurityCredentialsDefines AWS security credentials. These are either retrieved from the AWS security_credentials endpoint or AWS environment variables.
CertificateIdentityPoolSubjectTokenSupplierProvider for retrieving the subject tokens for IdentityPoolCredentials by reading an X.509 certificate from the filesystem. The certificate file (e.g., PEM or DER encoded) is read, the leaf certificate is base64-encoded (DER format), wrapped in a JSON array, and used as the subject token for STS exchange.
ClientIdAn OAuth2 user authorization Client ID and associated information.
Corresponds to the information in the json file downloadable for a Client ID.
ClientId.Builder CloudShellCredentialsOAuth2 credentials representing the built-in service account for Google Cloud Shell.
CloudShellCredentials.Builder ComputeEngineCredentialsOAuth2 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 CredentialAccessBoundaryDefines an upper bound of permissions available for a GCP credential via AccessBoundaryRules.
CredentialAccessBoundary.AccessBoundaryRuleDefines 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.
DownscopedCredentialsDownscopedCredentials enables the ability to downscope, or restrict, the Identity and Access Management (IAM) permissions that a short-lived credential can use for Cloud Storage.
This class provides a server-side approach for generating downscoped tokens, suitable for situations where Credential Access Boundary rules change infrequently or a single downscoped credential is reused many times. For scenarios where rules change frequently, or you need to generate many unique downscoped tokens, the client-side approach using com.google.auth.credentialaccessboundary.ClientSideCredentialAccessBoundaryFactory
is more efficient.
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.
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.BuilderOAuth2 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.BuilderBuilder for ExternalAccountAuthorizedUserCredentials.
ExternalAccountCredentialsBase external account credentials class.
Handles initializing external credentials, calls to the Security Token Service, and service account impersonation.
ExternalAccountCredentials.BuilderBase builder for external account credentials.
ExternalAccountSupplierContextContext 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 GoogleAuthUtilsThis 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
GoogleCredentialsBase type for credentials for authorizing calls to Google APIs using OAuth2.
GoogleCredentials.Builder IdTokenRepresents a temporary IdToken and its JsonWebSignature object
IdTokenCredentialsIdTokenCredentials 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 IdentityPoolCredentialSourceThe IdentityPool credential source. Dictates the retrieval method of the external credential, which can either be through a metadata server or a local file.
IdentityPoolCredentialSource.CertificateConfigRepresents the configuration options for X.509-based workload credentials (mTLS). It specifies how to locate and use the client certificate, private key, and optional trust chain for mutual TLS authentication.
IdentityPoolCredentialsUrl-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 ImpersonatedCredentialsImpersonatedCredentials 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 JwtClaimsValue 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.
OAuth2CredentialsBase type for Credentials using OAuth2.
OAuth2Credentials.Builder OAuth2CredentialsWithRefreshA refreshable alternative to OAuth2Credentials.
To enable automatic token refreshes, you must provide an OAuth2RefreshHandler.
OAuth2CredentialsWithRefresh.Builder OAuth2UtilsInternal utilities for the com.google.auth.oauth2 namespace.
These classes are marked public but should be treated effectively as internal classes only. They are not subject to any backwards compatibility guarantees and might change or be removed at any time. They are provided only as a convenience for other libraries within the com.google.auth
family. Application developers should avoid using these classes directly; they are not part of the public API.
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" } } }
PluggableAuthCredentialsPluggableAuthCredentials 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 SecureSessionAgentUtilities to fetch the S2A (Secure Session Agent) address from the mTLS configuration.
mTLS configuration is queried from the MDS MTLS Autoconfiguration endpoint. See https://google.aip.dev/auth/4115 for details.
This is an experimental utility.
SecureSessionAgent.Builder SecureSessionAgentConfigHolds an mTLS configuration (consists of address of S2A) retrieved from the Metadata Server.
SecureSessionAgentConfig.Builder ServiceAccountCredentialsOAuth2 credentials representing a Service Account for calling Google APIs.
By default uses a JSON Web Token (JWT) to fetch access tokens.
ServiceAccountCredentials.Builder ServiceAccountJwtAccessCredentialsService 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 StsRequestHandlerImplements the OAuth 2.0 token exchange based on RFC 8693.
This class handles the process of exchanging one type of token for another using the Security Token Service (STS). It constructs and sends the token exchange request to the STS endpoint and parses the response to create an StsTokenExchangeResponse object.
Use the #newBuilder(String, StsTokenExchangeRequest, HttpRequestFactory) method to create a new builder for constructing an instance of this class.
StsRequestHandler.Builder StsTokenExchangeRequestRepresents an OAuth 2.0 token exchange request, as defined in RFC 8693, Section 2.1.
This class encapsulates the parameters necessary for making a token exchange request to Google Security Token Service (STS). It includes the subject token, subject token type, optional parameters like acting party, scopes, resource, audience, requested token type, and internal options.
Instances of this class are immutable. Use the #newBuilder(String, String) method to create a new builder.
StsTokenExchangeRequest.Builder StsTokenExchangeResponseRepresents a successful OAuth 2.0 token exchange response from the Google Security Token Service (STS), as defined in RFC 8693, Section 2.2.1.
This class provides access to the exchanged access token, issued token type, token type, expiration time, refresh token (optional), scopes (optional), and the access boundary session key (optional).
Instances are immutable. Use #newBuilder(String, String, String) to create an instance.
StsTokenExchangeResponse.Builder TokenVerifierHandle verification of Google-signed JWT tokens.
TokenVerifier.Builder UserAuthorizerHandles an interactive 3-Legged-OAuth2 (3LO) user consent authorization.
UserAuthorizer.Builder UserAuthorizer.TokenResponseWithConfigRepresents 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 AwsSecurityCredentialsSupplierSupplier for retrieving AWS Security credentials for AwsCredentials to exchange for GCP access tokens.
IdTokenProviderInterface for an Google OIDC token provider. This type represents a google issued OIDC token.
IdentityPoolSubjectTokenSupplier JwtProviderInterface for creating custom JWT tokens
OAuth2Credentials.CredentialsChangedListenerListener 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.OAuth2RefreshHandlerInterface for the refresh handler.
PKCEProvider QuotaProjectIdProviderInterface for GoogleCredentials that return a quota project ID.
TokenStoreInterface for long term storage of tokens
Enums ComputeEngineCredentials.BindingEnforcementExperimental Feature.
BindingEnforcement specifies how binding info in tokens will be enforced.
Behavior of setting GoogleAuthTransport / BindingEnforcement:
MTLS-bound token where binding enforcement depends on IAM policy: MTLS / {}, {} / IAM_POLICY, MTLS / IAM_POLICY
MTLS-bound token where bindings are always enforced: {} / ON, MTLS / ON
DirectPath bound token: ALTS / {}
ComputeEngineCredentials.GoogleAuthTransportExperimental Feature.
GoogleAuthTransport specifies how to authenticate to Google APIs.
Behavior of setting GoogleAuthTransport / BindingEnforcement:
MTLS-bound token where binding enforcement depends on IAM policy: MTLS / IAM_POLICY
MTLS-bound token where bindings are always enforced: MTLS / ON
DirectPath bound token: ALTS / {}
ExternalAccountCredentials.SubjectTokenTypesEnum specifying values for the subjectTokenType field in ExternalAccountCredentials
.
Enum of various credential-specific options to apply to the token.
ComputeEngineCredentials
ImpersonatedCredential
Represents the client authentication types as specified in RFC 7591.
For more details, see RFC 7591.
Exceptions TokenVerifier.VerificationExceptionCustom exception for wrapping all verification errors.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4