From 6371bc513915e0380058e12c579bcf78f97019d1 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 4 Dec 2026 06:39:39 +0000 Subject: [PATCH] docs(auth): clarify ID token and TokenVerifier Javadocs --- .../java/com/google/auth/oauth2/IdToken.java | 45 ++++++-- .../auth/oauth2/IdTokenCredentials.java | 83 ++++++++++++-- .../google/auth/oauth2/IdTokenProvider.java | 68 ++++++++---- .../com/google/auth/oauth2/TokenVerifier.java | 104 +++++++++++++++--- .../google/auth/oauth2/UserCredentials.java | 20 +++- 5 files changed, 256 insertions(+), 64 deletions(-) diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdToken.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdToken.java index e612d9548c49..33e6e04fe5e1 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdToken.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdToken.java @@ -43,7 +43,24 @@ import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; -/** Represents a temporary IdToken and its JsonWebSignature object */ +/** + * Represents a temporary Google-signed OpenID Connect (OIDC) ID token. + * + *

This class extends {@link AccessToken}: {@link AccessToken#getTokenValue()} returns the raw + * encoded JWT string, and {@link AccessToken#getExpirationTime()} returns the expiration time + * parsed from the token's {@code exp} claim. + * + *

The {@link #create(String)} factory methods parse the JWT structure only. They do not verify + * the cryptographic signature, audience, issuer, or expiration. To verify an incoming ID token, use + * {@link TokenVerifier}. + * + *

For more information on identity tokens, see Identity + * tokens. + * + * @see IdTokenCredentials + * @see TokenVerifier + */ @NullMarked public class IdToken extends AccessToken implements Serializable { @@ -61,23 +78,31 @@ private IdToken(String tokenValue, JsonWebSignature jsonWebSignature) { } /** - * Creates an IdToken given the encoded Json Web Signature. + * Parses an encoded JWT into an {@link IdToken} using the default JSON factory. * - * @param tokenValue String representation of the ID token. - * @throws IOException if JWT token parsing fails - * @return returns com.google.auth.oauth2.IdToken + *

This method does not verify the token's signature or claims. Use {@link TokenVerifier} to + * validate incoming tokens. Throws {@code NullPointerException} if the parsed JWT payload does + * not contain an {@code exp} claim. + * + * @param tokenValue the encoded JWT string + * @return the parsed {@link IdToken} + * @throws IOException if parsing the JWT fails */ public static IdToken create(String tokenValue) throws IOException { return create(tokenValue, OAuth2Utils.JSON_FACTORY); } /** - * Creates an IdToken given the encoded Json Web Signature and JSON Factory + * Parses an encoded JWT into an {@link IdToken} using the specified {@link JsonFactory}. * - * @param jsonFactory JsonFactory to use for parsing the provided token. - * @param tokenValue String representation of the ID token. - * @throws IOException if JWT token parsing fails - * @return returns com.google.auth.oauth2.IdToken + *

This method does not verify the token's signature or claims. Use {@link TokenVerifier} to + * validate incoming tokens. Throws {@code NullPointerException} if the parsed JWT payload does + * not contain an {@code exp} claim. + * + * @param tokenValue the encoded JWT string + * @param jsonFactory the {@link JsonFactory} used to parse the JWT + * @return the parsed {@link IdToken} + * @throws IOException if parsing the JWT fails */ public static IdToken create(String tokenValue, JsonFactory jsonFactory) throws IOException { return new IdToken(tokenValue, JsonWebSignature.parse(jsonFactory, tokenValue)); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdTokenCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdTokenCredentials.java index 3c0a17dce1f1..7e86ad724718 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdTokenCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdTokenCredentials.java @@ -42,12 +42,26 @@ import org.jspecify.annotations.Nullable; /** - * IdTokenCredentials provides a Google-issued OpenID Connect (OIDC) ID token. + * Credentials that provide a Google-signed OpenID Connect (OIDC) ID token as a bearer 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 ID tokens: - * {@link ServiceAccountCredentials}, {@link ComputeEngineCredentials}, and {@link - * ImpersonatedCredentials}. + *

Use an ID token to call services that verify the caller's audience, such as Cloud Run, Cloud + * Run functions, or Identity-Aware Proxy (IAP). The following {@link IdTokenProvider} + * implementations support setting a target audience: {@link ServiceAccountCredentials}, {@link + * ComputeEngineCredentials}, and {@link ImpersonatedCredentials}. + * + *

Although {@link UserCredentials} implements {@link IdTokenProvider}, it ignores {@code + * targetAudience} and issues tokens whose {@code aud} claim is the OAuth client ID. Services that + * check the audience claim, such as Cloud Run and IAP, reject those tokens with HTTP 401 or 403. + * For local development with {@code gcloud} user ADC, wrap the credentials in {@link + * ImpersonatedCredentials} or run {@code gcloud auth application-default login + * --impersonate-service-account}. {@link ExternalAccountCredentials} does not implement {@link + * IdTokenProvider} directly and must also be wrapped in {@link ImpersonatedCredentials} to obtain + * ID tokens. + * + *

Like {@link OAuth2Credentials}, tokens are fetched lazily. Calling {@link #getIdToken()} + * returns {@code null} until {@link OAuth2Credentials#refreshIfExpired()}, {@link + * OAuth2Credentials#refresh()}, or {@link OAuth2Credentials#getRequestMetadata(java.net.URI)} has + * fetched a token. * *

For more information, see Get an ID token. @@ -127,6 +141,10 @@ * System.out.println(jws.getPayload().getAudienceAsList()); * System.out.println(jws.getPayload().getExpirationTimeSeconds()); * } + * + * @see IdTokenProvider + * @see IdToken + * @see TokenVerifier */ @NullMarked public class IdTokenCredentials extends OAuth2Credentials { @@ -148,11 +166,28 @@ private IdTokenCredentials(Builder builder) { this.options = builder.getOptions(); } + /** + * Requests a fresh {@link IdToken} from the underlying {@link IdTokenProvider} using the + * configured target audience and options. + * + * @return the newly fetched {@link IdToken} + * @throws IOException if the underlying provider fails to issue an ID token + */ @Override public AccessToken refreshAccessToken() throws IOException { return this.idTokenProvider.idTokenWithAudience(targetAudience, options); } + /** + * Returns the most recently fetched {@link IdToken}, or {@code null} if no token has been fetched + * yet. + * + *

Tokens are fetched lazily. Call {@link OAuth2Credentials#refreshIfExpired()} or {@link + * OAuth2Credentials#refresh()} before calling this method to ensure a non-null, non-expired + * token. + * + * @return the current {@link IdToken}, or {@code null} before the first refresh + */ public @Nullable IdToken getIdToken() { return (IdToken) getAccessToken(); } @@ -217,6 +252,8 @@ protected Builder() {} /** * Sets the provider for the ID token. * + *

Throws {@code NullPointerException} if {@code idTokenProvider} is {@code null}. + * * @param idTokenProvider the provider for the ID token, cannot be null * @return the builder object */ @@ -226,6 +263,11 @@ public Builder setIdTokenProvider(IdTokenProvider idTokenProvider) { return this; } + /** + * Returns the configured ID token provider, or {@code null} if not set. + * + * @return the ID token provider, or {@code null} + */ public @Nullable IdTokenProvider getIdTokenProvider() { return this.idTokenProvider; } @@ -233,8 +275,11 @@ public Builder setIdTokenProvider(IdTokenProvider idTokenProvider) { /** * Sets the target audience for the ID token. * - * @param targetAudience the target audience, cannot be null for non-UserCredentials. If set for - * UserCredentials, the value will be ignored. + *

Required when {@link #build()} is called with any provider other than {@link + * UserCredentials}. If set for {@link UserCredentials}, this value is ignored. + * + * @param targetAudience the target audience, cannot be null for providers other than {@link + * UserCredentials} * @return the builder object */ @CanIgnoreReturnValue @@ -243,14 +288,21 @@ public Builder setTargetAudience(@Nullable String targetAudience) { return this; } + /** + * Returns the configured target audience, or {@code null} if not set. + * + * @return the target audience, or {@code null} + */ public @Nullable String getTargetAudience() { return this.targetAudience; } /** - * Sets the options for the ID token. + * Sets the provider-specific options for the ID token. + * + *

Each {@link IdTokenProvider} honors only its supported options and ignores others. * - * @param options list of options, can be null or empty if no options are needed. + * @param options list of options, or {@code null} or empty if no options are needed * @return the builder object */ @CanIgnoreReturnValue @@ -259,10 +311,23 @@ public Builder setOptions(@Nullable List options) { return this; } + /** + * Returns the configured provider options, or {@code null} if not set. + * + * @return the list of options, or {@code null} + */ public @Nullable List getOptions() { return this.options; } + /** + * Builds an {@link IdTokenCredentials} instance from this builder. + * + *

Throws {@code NullPointerException} if no {@link IdTokenProvider} was set, or if no target + * audience was set for a provider other than {@link UserCredentials}. + * + * @return a new {@link IdTokenCredentials} instance + */ @Override public IdTokenCredentials build() { return new IdTokenCredentials(this); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdTokenProvider.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdTokenProvider.java index 40601a4747de..e17f74030a13 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdTokenProvider.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IdTokenProvider.java @@ -36,31 +36,49 @@ import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; -/** Interface for an Google OIDC token provider. This type represents a google issued OIDC token. */ +/** + * Interface for credentials that can issue Google-signed OpenID Connect (OIDC) ID tokens. + * + *

Implementations include {@link ServiceAccountCredentials}, {@link ComputeEngineCredentials}, + * {@link ImpersonatedCredentials}, and {@link UserCredentials}. Wrap a provider in {@link + * IdTokenCredentials} to cache, automatically refresh, and attach ID tokens to outgoing requests. + * + *

For details on getting ID tokens in different environments, see Get an ID token. + * + * @see IdTokenCredentials + * @see IdToken + */ @NullMarked public interface IdTokenProvider { /** - * Enum of various credential-specific options to apply to the token. + * Credential-specific options that customize the requested ID token. * - *

ComputeEngineCredentials + *

Each {@link IdTokenProvider} honors only the options it supports and ignores all others: * *

- * - *
- * ImpersonatedCredential - * - * */ public enum Option { + /** + * Requests full metadata claims ({@code format=full}) in the ID token, including project and + * instance details. Supported only by {@link ComputeEngineCredentials}. + */ FORMAT_FULL("formatFull"), + /** + * Requests VM license codes ({@code licenses=TRUE}, which also enables {@code format=full}) in + * the ID token. Supported only by {@link ComputeEngineCredentials}. + */ LICENSES_TRUE("licensesTrue"), + /** + * Requests that the impersonated service account email address be included in the ID token + * claims ({@code includeEmail=true}). Supported only by {@link ImpersonatedCredentials}. + */ INCLUDE_EMAIL("includeEmail"), /** * Requests an ID token that is not bound to the workload's agent identity certificate. @@ -90,21 +108,29 @@ private Option(String option) { this.option = option; } + /** + * Returns the string identifier for this option. + * + * @return the option identifier + */ public String getOption() { return option; } } /** - * Returns a Google OpenID Token with the provided audience field. + * Returns a Google-signed OpenID Connect (OIDC) ID token for the given target audience. + * + *

Most providers require a non-null {@code targetAudience} and set it as the token's {@code + * aud} claim. {@link UserCredentials} is an exception: it ignores {@code targetAudience} and + * returns an ID token whose {@code aud} claim is the credential's OAuth client ID. * - * @param targetAudience List of audiences the issued ID Token should be valid for. targetAudience - * accepts a single string value (multiple audiences are not supported) - * @param options List of Credential specific options for the token. For example, an IDToken for a - * {@link ComputeEngineCredentials} can return platform specific claims if {@link - * IdTokenProvider.Option#FORMAT_FULL} is provided as a list option. - * @throws IOException if token creation fails - * @return IdToken object which includes the raw id_token, expiration and audience. + * @param targetAudience the single target audience string for the issued ID token (multiple + * audiences are not supported). Ignored by {@link UserCredentials}. + * @param options optional provider-specific options, or {@code null} to use provider defaults. + * Unsupported options are ignored. + * @return the issued {@link IdToken}, including the encoded JWT and its expiration time + * @throws IOException if requesting or parsing the ID token fails */ IdToken idTokenWithAudience(@Nullable String targetAudience, @Nullable List

Always configure both the expected {@link TokenVerifier.Builder#setAudience(String) audience} + * and {@link TokenVerifier.Builder#setIssuer(String) issuer} before calling {@link + * #verify(String)}. Both checks are optional: if either is left unset, {@code TokenVerifier} skips + * checking that claim and accepts any valid Google-signed token regardless of audience or issuer. + * + *

Only {@code RS256} and {@code ES256} signing algorithms are supported. Unless a fixed key is + * configured with {@link TokenVerifier.Builder#setPublicKey(PublicKey)}, public keys are fetched + * from {@link TokenVerifier.Builder#setCertificatesLocation(String)} (defaulting to {@code + * https://www.googleapis.com/oauth2/v3/certs} for {@code RS256} and {@code + * https://www.gstatic.com/iap/verify/public_key-jwk} for {@code ES256}) and cached in memory for 1 + * hour. Both JWKS and X.509 PEM certificate endpoints are supported. + * + *

Instances are thread-safe and cache fetched public keys internally. Reuse a single {@code + * TokenVerifier} instance across requests rather than building a new one for each token. + * + *

Usage: + * + *

{@code
+ * TokenVerifier verifier =
+ *     TokenVerifier.newBuilder()
+ *         .setAudience("https://my-service.a.run.app")
+ *         .setIssuer("https://accounts.google.com")
+ *         .build();
+ * JsonWebSignature verified = verifier.verify(rawJwt);
+ * String subject = verified.getPayload().getSubject();
+ * }
+ * + *

For more information, see Get an ID token and Securing your app with signed + * headers. * * @author Jeff Ching * @since 0.21.0 + * @see IdTokenCredentials + * @see IdToken */ @NullMarked public class TokenVerifier { @@ -109,6 +144,12 @@ private TokenVerifier(Builder builder) { .build(new PublicKeyLoader(builder.httpTransportFactory)); } + /** + * Creates a new builder configured with {@code Clock.SYSTEM} and the default HTTP transport + * factory. + * + * @return a new {@link TokenVerifier.Builder} + */ public static Builder newBuilder() { return new Builder() .setClock(Clock.SYSTEM) @@ -116,11 +157,27 @@ public static Builder newBuilder() { } /** - * Verify an encoded JWT token. + * Parses and verifies an encoded JWT. + * + *

Checks performed: * - * @param token encoded JWT token - * @return the parsed JsonWebSignature instance for additional validation if necessary - * @throws VerificationException thrown if any verification fails + *

+ * + * @param token the encoded JWT string to verify + * @return the verified {@link JsonWebSignature} for reading additional claims + * @throws VerificationException if parsing, claim checks, key retrieval, or signature + * verification fails */ public JsonWebSignature verify(String token) throws VerificationException { JsonWebSignature jsonWebSignature; @@ -201,10 +258,12 @@ public static class Builder { private HttpTransportFactory httpTransportFactory; /** - * Set a target audience to verify. + * Sets the expected {@code aud} claim to verify using exact string equality. * - * @param audience the audience claim to verify - * @return the builder + *

If not set, audience verification is skipped. + * + * @param audience the expected audience claim + * @return this builder */ public Builder setAudience(String audience) { this.audience = audience; @@ -212,11 +271,14 @@ public Builder setAudience(String audience) { } /** - * Override the location URL that contains published public keys. Defaults to well-known Google - * locations. + * Overrides the URL used to fetch published public keys (JWKS or X.509 PEM certificate map). * - * @param certificatesLocation URL to published public keys - * @return the builder + *

If not set, defaults to {@code https://www.googleapis.com/oauth2/v3/certs} for {@code + * RS256} tokens and {@code https://www.gstatic.com/iap/verify/public_key-jwk} for {@code ES256} + * tokens. Ignored if {@link #setPublicKey(PublicKey)} is also set. + * + * @param certificatesLocation URL serving published public keys + * @return this builder */ public Builder setCertificatesLocation(String certificatesLocation) { this.certificatesLocation = certificatesLocation; @@ -224,10 +286,14 @@ public Builder setCertificatesLocation(String certificatesLocation) { } /** - * Set the issuer to verify. + * Sets the expected {@code iss} claim to verify using exact string equality (for example, + * {@code "https://accounts.google.com"} for Google OIDC ID tokens or {@code + * "https://cloud.google.com/iap"} for IAP assertions). * - * @param issuer the issuer claim to verify - * @return the builder + *

If not set, issuer verification is skipped. + * + * @param issuer the expected issuer claim + * @return this builder */ public Builder setIssuer(String issuer) { this.issuer = issuer; @@ -235,11 +301,13 @@ public Builder setIssuer(String issuer) { } /** - * Set the PublicKey for verifying the signature. This will ignore the key id from the JWT token - * header. + * Sets a fixed {@link PublicKey} for verifying the JWT signature. + * + *

When set, this key is used directly and both {@link #setCertificatesLocation(String)} and + * the JWT header's {@code kid} are ignored. * * @param publicKey the public key to validate the signature - * @return the builder + * @return this builder */ public Builder setPublicKey(PublicKey publicKey) { this.publicKey = publicKey; diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java index 35d37f3d727c..90dfb3622a04 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java @@ -223,13 +223,21 @@ public AccessToken refreshAccessToken() throws IOException { } /** - * Returns a Google ID Token from the refresh token response. + * Returns the OIDC ID token included in an OAuth 2.0 token refresh response. * - * @param targetAudience This can't be used for UserCredentials. - * @param options list of Credential specific options for the token. Currently unused for - * UserCredentials. - * @throws IOException if the attempt to get an IdToken failed - * @return IdToken object which includes the raw id_token, expiration and audience + *

Both {@code targetAudience} and {@code options} are ignored. The issued ID token's {@code + * aud} claim is always this credential's OAuth client ID, so services that validate the audience + * claim (such as Cloud Run and Identity-Aware Proxy) will reject it. To obtain an audience-scoped + * ID token during local development, wrap these credentials in {@link ImpersonatedCredentials} or + * run {@code gcloud auth application-default login --impersonate-service-account}. + * + *

Throws {@code IllegalStateException} if this credential has no refresh token. + * + * @param targetAudience ignored by {@code UserCredentials} + * @param options ignored by {@code UserCredentials} + * @return the {@link IdToken} returned by the refresh token response + * @throws IOException if the refresh request fails, the configured universe domain is not the + * default Google universe, or the token response does not include an {@code id_token} */ @Override public IdToken idTokenWithAudience(String targetAudience, List