From 6371bc513915e0380058e12c579bcf78f97019d1 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 4 Dec 2026 06:39:39 +0000 Subject: [PATCH 1/3] 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

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. + *

This class extends {@link AccessToken}. Calling {@link AccessToken#getTokenValue() + * getTokenValue()} returns the raw encoded JWT string, and calling {@link + * AccessToken#getExpirationTime() getExpirationTime()} returns the expiration time parsed from the + * token's {@code exp} claim. Other JWT claims are not exposed directly on this class. Use {@link + * TokenVerifier} to verify and read claims from an incoming token, or {@code + * JsonWebSignature.parse} to inspect claims. * - *

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}. + *

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

For more information on identity tokens, see Identity @@ -81,12 +83,14 @@ private IdToken(String tokenValue, JsonWebSignature jsonWebSignature) { * Parses an encoded JWT into an {@link IdToken} using the default JSON factory. * *

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. + * validate incoming tokens. Throws {@code IllegalArgumentException} if {@code tokenValue} does + * not have three dot-separated JWT segments or lacks an {@code alg} header, and {@code + * NullPointerException} if {@code tokenValue} is {@code null} or 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 + * @throws IOException if parsing the JWT JSON fails */ public static IdToken create(String tokenValue) throws IOException { return create(tokenValue, OAuth2Utils.JSON_FACTORY); @@ -96,13 +100,15 @@ public static IdToken create(String tokenValue) throws IOException { * Parses an encoded JWT into an {@link IdToken} using the specified {@link JsonFactory}. * *

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. + * validate incoming tokens. Throws {@code IllegalArgumentException} if {@code tokenValue} does + * not have three dot-separated JWT segments or lacks an {@code alg} header, and {@code + * NullPointerException} if either argument is {@code null} or 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 + * @throws IOException if parsing the JWT JSON 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 7e86ad724718..160beb628094 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 @@ -49,19 +49,20 @@ * implementations support setting a target audience: {@link ServiceAccountCredentials}, {@link * ComputeEngineCredentials}, and {@link ImpersonatedCredentials}. * - *

Although {@link UserCredentials} implements {@link IdTokenProvider}, it ignores {@code + *

Although {@link UserCredentials} implements {@code 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. + * validate the audience claim against their own URL or resource ID (such as IAP, or Cloud Run when + * using {@code gcloud auth application-default login}) reject these tokens. 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=SERVICE_ACCOUNT_EMAIL} + * so ADC loads impersonated credentials instead. {@link ExternalAccountCredentials} does not + * implement {@code IdTokenProvider} directly and must also be wrapped in {@code + * 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. + *

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

For more information, see Get an ID token. @@ -75,11 +76,12 @@ * * // Choose one of the following ways to create IdTokenCredentials: * - * // 1. From Application Default Credentials (as ServiceAccountCredentials) + * // 1. From Application Default Credentials (for example, ServiceAccountCredentials, + * // ComputeEngineCredentials, or ImpersonatedCredentials) * // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/svc.json * GoogleCredentials adcCreds = GoogleCredentials.getApplicationDefault(); - * if (!(adcCreds instanceof IdTokenProvider)) { - * throw new IllegalStateException("Credentials do not support ID tokens."); + * if (!(adcCreds instanceof IdTokenProvider) || adcCreds instanceof UserCredentials) { + * throw new IllegalStateException("Credentials do not support audience-scoped ID tokens."); * } * * tokenCredential = @@ -91,9 +93,6 @@ * // 2. From ServiceAccountCredentials * ServiceAccountCredentials saCreds = * ServiceAccountCredentials.fromStream(new FileInputStream(credPath)); - * saCreds = - * (ServiceAccountCredentials) - * saCreds.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform")); * tokenCredential = * IdTokenCredentials.newBuilder() * .setIdTokenProvider(saCreds) @@ -109,10 +108,12 @@ * .setOptions(Arrays.asList(IdTokenProvider.Option.FORMAT_FULL)) * .build(); * - * // 4. From ImpersonatedCredentials (using saCreds from option 2 as source credentials) + * // 4. From ImpersonatedCredentials (using scoped saCreds from option 2 as source credentials) + * GoogleCredentials scopedSource = + * saCreds.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform")); * ImpersonatedCredentials imCreds = * ImpersonatedCredentials.create( - * saCreds, + * scopedSource, * "impersonated-account@project.iam.gserviceaccount.com", * null, * Arrays.asList("https://www.googleapis.com/auth/cloud-platform"), @@ -179,14 +180,15 @@ public AccessToken refreshAccessToken() throws IOException { } /** - * Returns the most recently fetched {@link IdToken}, or {@code null} if no token has been fetched - * yet. + * Returns the cached {@link IdToken} without triggering a refresh. * - *

Tokens are fetched lazily. Call {@link OAuth2Credentials#refreshIfExpired()} or {@link - * OAuth2Credentials#refresh()} before calling this method to ensure a non-null, non-expired - * token. + *

Tokens are fetched lazily. The returned token may be {@code null} before the first refresh, + * or expired. Call {@link OAuth2Credentials#refreshIfExpired() refreshIfExpired()} (or {@link + * OAuth2Credentials#refresh() refresh()} to force a new fetch, or {@link + * OAuth2Credentials#getRequestMetadata(java.net.URI) getRequestMetadata(URI)}) before calling + * this method to ensure a non-null, non-expired token. * - * @return the current {@link IdToken}, or {@code null} before the first refresh + * @return the cached {@link IdToken}, or {@code null} before the first refresh */ public @Nullable IdToken getIdToken() { return (IdToken) getAccessToken(); @@ -241,6 +243,12 @@ public static Builder newBuilder() { return new Builder(); } + /** + * Builder for {@link IdTokenCredentials}. + * + *

Inherited {@link OAuth2Credentials.Builder} setters ({@code setAccessToken}, {@code + * setRefreshMargin}, and {@code setExpirationMargin}) are ignored by {@link #build() build()}. + */ public static class Builder extends OAuth2Credentials.Builder { private @Nullable IdTokenProvider idTokenProvider; @@ -255,7 +263,7 @@ protected Builder() {} *

Throws {@code NullPointerException} if {@code idTokenProvider} is {@code null}. * * @param idTokenProvider the provider for the ID token, cannot be null - * @return the builder object + * @return this builder */ @CanIgnoreReturnValue public Builder setIdTokenProvider(IdTokenProvider idTokenProvider) { @@ -275,12 +283,11 @@ public Builder setIdTokenProvider(IdTokenProvider idTokenProvider) { /** * Sets the target audience for the ID token. * - *

Required when {@link #build()} is called with any provider other than {@link - * UserCredentials}. If set for {@link UserCredentials}, this value is ignored. + *

Required when {@link #build() build()} is called with any provider other than {@link + * UserCredentials}. If set for {@code UserCredentials}, this value is ignored. * - * @param targetAudience the target audience, cannot be null for providers other than {@link - * UserCredentials} - * @return the builder object + * @param targetAudience the target audience (ignored by {@code UserCredentials}) + * @return this builder */ @CanIgnoreReturnValue public Builder setTargetAudience(@Nullable String targetAudience) { @@ -303,7 +310,7 @@ public Builder setTargetAudience(@Nullable String targetAudience) { *

Each {@link IdTokenProvider} honors only its supported options and ignores others. * * @param options list of options, or {@code null} or empty if no options are needed - * @return the builder object + * @return this builder */ @CanIgnoreReturnValue public Builder setOptions(@Nullable List options) { 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 e17f74030a13..f2c37dd74cd2 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 @@ -40,8 +40,9 @@ * 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. + * {@link ImpersonatedCredentials}, and {@link UserCredentials} (which ignores {@code + * targetAudience}). 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. @@ -58,10 +59,11 @@ public interface IdTokenProvider { *

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

*/ public enum Option { @@ -121,9 +123,10 @@ public String getOption() { /** * 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. + *

All built-in providers except {@link UserCredentials} require a non-null {@code + * targetAudience} and set it as the token's {@code aud} claim. {@code UserCredentials} ignores + * {@code targetAudience} and returns an ID token whose {@code aud} claim is the credential's + * OAuth client ID. * * @param targetAudience the single target audience string for the issued ID token (multiple * audiences are not supported). Ignored by {@link UserCredentials}. diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java index 5bbbf0a4a88a..437087cf65d4 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java @@ -81,17 +81,18 @@ * Verifies Google-signed JWTs, such as OpenID Connect (OIDC) ID tokens and Identity-Aware Proxy * (IAP) assertions. * - *

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. + *

Configure both the expected {@link TokenVerifier.Builder#setAudience(String) audience} and + * {@link TokenVerifier.Builder#setIssuer(String) issuer} in production. Neither check is enabled by + * default: if either is left unset, {@code TokenVerifier} skips validating that claim and accepts + * any token with a valid signature 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. + * configured with {@link TokenVerifier.Builder#setPublicKey(PublicKey) setPublicKey}, public keys + * are fetched from {@link TokenVerifier.Builder#setCertificatesLocation(String) + * setCertificatesLocation} (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 without refreshing on unknown key IDs. 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. @@ -109,7 +110,10 @@ * } * *

For more information, see Get an ID token and Identity + * tokens, Validating + * an ID token, and Securing your app with signed * headers. * @@ -162,21 +166,30 @@ public static Builder newBuilder() { *

Checks performed: * *

* + *

This method does not validate {@code iat} or {@code nbf} claims and applies no clock skew + * tolerance to {@code exp}. Inspect additional claims on the returned {@link JsonWebSignature} as + * needed. + * + *

Throws {@code IllegalArgumentException} if {@code token} does not have three dot-separated + * JWT segments or lacks an {@code alg} header, and {@code NullPointerException} if {@code token} + * is {@code null}, rather than {@link TokenVerifier.VerificationException VerificationException}. + * * @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 + * @throws VerificationException if JSON parsing, claim checks, key retrieval, or signature * verification fails */ public JsonWebSignature verify(String token) throws VerificationException { @@ -249,6 +262,14 @@ private String getCertificateLocation(JsonWebSignature jsonWebSignature) throw new VerificationException("Unknown algorithm"); } + /** + * Builder for {@link TokenVerifier}. + * + *

Obtain an instance via {@link TokenVerifier#newBuilder() TokenVerifier.newBuilder()}, which + * configures the default system clock and HTTP transport factory. Calling {@code new + * TokenVerifier.Builder()} directly leaves those unset and causes {@link + * TokenVerifier#verify(String) verify(String)} to throw {@code NullPointerException}. + */ public static class Builder { private String audience; private String certificatesLocation; @@ -258,7 +279,8 @@ public static class Builder { private HttpTransportFactory httpTransportFactory; /** - * Sets the expected {@code aud} claim to verify using exact string equality. + * Sets the expected {@code aud} claim to verify using exact string equality (tokens whose + * {@code aud} claim is a JSON array will not match). * *

If not set, audience verification is skipped. * @@ -275,7 +297,7 @@ public Builder setAudience(String audience) { * *

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. + * tokens. Ignored if {@link #setPublicKey(PublicKey) setPublicKey} is also set. * * @param certificatesLocation URL serving published public keys * @return this builder @@ -303,8 +325,8 @@ public Builder setIssuer(String issuer) { /** * 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. + *

When set, this key is used directly and both {@link #setCertificatesLocation(String) + * setCertificatesLocation} and the JWT header's {@code kid} are ignored. * * @param publicKey the public key to validate the signature * @return this builder @@ -315,10 +337,11 @@ public Builder setPublicKey(PublicKey publicKey) { } /** - * Set the clock for checking token expiry. Used for testing. + * Sets the {@link Clock} used to check token expiration. Defaults to {@code Clock.SYSTEM} when + * created with {@link TokenVerifier#newBuilder() TokenVerifier.newBuilder()}. * - * @param clock the clock to use. Defaults to the system clock - * @return the builder + * @param clock the clock to use + * @return this builder */ public Builder setClock(Clock clock) { this.clock = clock; @@ -326,11 +349,12 @@ public Builder setClock(Clock clock) { } /** - * Set the HttpTransportFactory used for requesting public keys from the certificate URL. Used - * mostly for testing. + * Sets the {@link HttpTransportFactory} used to request public keys from the certificate URL. + * Defaults to the library's default transport factory when created with {@link + * TokenVerifier#newBuilder() TokenVerifier.newBuilder()}. * - * @param httpTransportFactory the HttpTransportFactory used to build certificate URL requests - * @return the builder + * @param httpTransportFactory the transport factory used to build certificate URL requests + * @return this builder */ public Builder setHttpTransportFactory(HttpTransportFactory httpTransportFactory) { this.httpTransportFactory = httpTransportFactory; @@ -338,9 +362,9 @@ public Builder setHttpTransportFactory(HttpTransportFactory httpTransportFactory } /** - * Build the custom TokenVerifier for verifying tokens. + * Builds a {@link TokenVerifier} from this builder. * - * @return the customized TokenVerifier + * @return the configured {@link TokenVerifier} */ public TokenVerifier build() { return new TokenVerifier(this); 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 90dfb3622a04..60c66f0c4460 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 @@ -227,9 +227,11 @@ public AccessToken refreshAccessToken() throws IOException { * *

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}. + * claim against their own URL or resource ID (such as Identity-Aware Proxy, or Cloud Run when + * using {@code gcloud auth application-default login}) 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=SERVICE_ACCOUNT_EMAIL}. * *

Throws {@code IllegalStateException} if this credential has no refresh token. * From 9fa7a4aa8bc8124687196f2b9028a713bc2018ca Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 4 Dec 2026 21:47:06 +0000 Subject: [PATCH 3/3] docs(auth): add DevSite source links for ID token behavior and clean up TokenVerifier tags --- .../auth/oauth2/IdTokenCredentials.java | 18 +++++++++------ .../google/auth/oauth2/IdTokenProvider.java | 22 +++++++++++++++---- .../com/google/auth/oauth2/TokenVerifier.java | 2 -- .../google/auth/oauth2/UserCredentials.java | 17 ++++++++------ 4 files changed, 39 insertions(+), 20 deletions(-) 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 160beb628094..e00106ec9111 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 @@ -50,13 +50,17 @@ * ComputeEngineCredentials}, and {@link ImpersonatedCredentials}. * *

Although {@link UserCredentials} implements {@code IdTokenProvider}, it ignores {@code - * targetAudience} and issues tokens whose {@code aud} claim is the OAuth client ID. Services that - * validate the audience claim against their own URL or resource ID (such as IAP, or Cloud Run when - * using {@code gcloud auth application-default login}) reject these tokens. 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=SERVICE_ACCOUNT_EMAIL} - * so ADC loads impersonated credentials instead. {@link ExternalAccountCredentials} does not - * implement {@code IdTokenProvider} directly and must also be wrapped in {@code + * targetAudience} because user ID + * tokens are always scoped to the OAuth client ID rather than a custom audience. To obtain an + * audience-scoped ID token during local development with {@code gcloud} user ADC, wrap the + * credentials in {@link ImpersonatedCredentials} (see Generate an + * ID token by impersonating a service account) or configure ADC + * with service account impersonation ({@code gcloud auth application-default login + * --impersonate-service-account=SERVICE_ACCOUNT_EMAIL}). {@link ExternalAccountCredentials} does + * not implement {@code IdTokenProvider} directly and must also be wrapped in {@code * ImpersonatedCredentials} to obtain ID tokens. * *

Like {@link OAuth2Credentials}, tokens are fetched lazily. Calling {@link #getIdToken() 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 f2c37dd74cd2..4de0aa588354 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 @@ -69,17 +69,27 @@ public interface IdTokenProvider { public enum Option { /** * Requests full metadata claims ({@code format=full}) in the ID token, including project and - * instance details. Supported only by {@link ComputeEngineCredentials}. + * instance details. Supported only by {@link ComputeEngineCredentials} because {@code format} + * is a query parameter of the Compute Engine metadata server's instance + * identity endpoint. */ 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}. + * the ID token. Supported only by {@link ComputeEngineCredentials} because {@code licenses} is + * a query parameter of the Compute Engine metadata server's instance + * identity endpoint. */ 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}. + * Requests that the impersonated service account's {@code email} and {@code email_verified} + * claims be included in the ID token ({@code includeEmail=true}). Supported only by {@link + * ImpersonatedCredentials} because {@code includeEmail} is a request field of the IAM + * Credentials API's projects.serviceAccounts.generateIdToken + * method. */ INCLUDE_EMAIL("includeEmail"), /** @@ -101,6 +111,10 @@ public enum Option { * whether to bind the ID token. Currently, it is bound whenever an agent identity certificate * is available and token binding is not globally disabled by {@code * GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN=false}. + * + *

For more information, see Request + * unbound ID tokens for specific targets. */ DISABLE_BOUND_ID_TOKEN("disableBoundIdToken"); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java index 437087cf65d4..58d4b3a0e93a 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/TokenVerifier.java @@ -117,8 +117,6 @@ * href="https://docs.cloud.google.com/iap/docs/signed-headers-howto">Securing your app with signed * headers. * - * @author Jeff Ching - * @since 0.21.0 * @see IdTokenCredentials * @see IdToken */ 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 60c66f0c4460..d831f62081ad 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 @@ -225,13 +225,16 @@ public AccessToken refreshAccessToken() throws IOException { /** * Returns the OIDC ID token included in an OAuth 2.0 token refresh response. * - *

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 against their own URL or resource ID (such as Identity-Aware Proxy, or Cloud Run when - * using {@code gcloud auth application-default login}) 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=SERVICE_ACCOUNT_EMAIL}. + *

Both {@code targetAudience} and {@code options} are ignored because user ID + * tokens are always scoped to the OAuth client ID rather than a custom audience. To obtain an + * audience-scoped ID token during local development, wrap these credentials in {@link + * ImpersonatedCredentials} (see Generate an + * ID token by impersonating a service account) or configure ADC + * with service account impersonation ({@code gcloud auth application-default login + * --impersonate-service-account=SERVICE_ACCOUNT_EMAIL}). * *

Throws {@code IllegalStateException} if this credential has no refresh token. *