Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,26 @@
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.
*
* <p>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.
*
* <p>The {@link #create(String) create} factory methods parse the JWT structure only. They do not
* verify the cryptographic signature, audience, issuer, or expiration.
*
* <p>For more information on identity tokens, see <a
* href="https://docs.cloud.google.com/docs/authentication/token-types#identity-tokens">Identity
* tokens</a>.
*
* @see IdTokenCredentials
* @see TokenVerifier
*/
@NullMarked
public class IdToken extends AccessToken implements Serializable {

Expand All @@ -61,23 +80,35 @@ 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
* <p>This method does not verify the token's signature or claims. Use {@link TokenVerifier} to
* 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 JSON 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
* <p>This method does not verify the token's signature or claims. Use {@link TokenVerifier} to
* 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 JSON fails
*/
public static IdToken create(String tokenValue, JsonFactory jsonFactory) throws IOException {
return new IdToken(tokenValue, JsonWebSignature.parse(jsonFactory, tokenValue));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,31 @@
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.
*
* <p>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}.
* <p>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}.
*
* <p>Although {@link UserCredentials} implements {@code IdTokenProvider}, it ignores {@code
* targetAudience} because <a
* href="https://docs.cloud.google.com/docs/authentication/token-types#user-id-tokens">user ID
* tokens</a> 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 <a
* href="https://docs.cloud.google.com/docs/authentication/get-id-token#impersonation">Generate an
* ID token by impersonating a service account</a>) or configure <a
* href="https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment#sa-impersonation">ADC
* with service account impersonation</a> ({@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.
*
* <p>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.
*
* <p>For more information, see <a
* href="https://docs.cloud.google.com/docs/authentication/get-id-token">Get an ID token</a>.
Expand All @@ -61,11 +80,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 =
Expand All @@ -77,9 +97,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)
Expand All @@ -95,10 +112,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"),
Expand Down Expand Up @@ -127,6 +146,10 @@
* System.out.println(jws.getPayload().getAudienceAsList());
* System.out.println(jws.getPayload().getExpirationTimeSeconds());
* }</pre>
*
* @see IdTokenProvider
* @see IdToken
* @see TokenVerifier
*/
@NullMarked
public class IdTokenCredentials extends OAuth2Credentials {
Expand All @@ -148,11 +171,29 @@ 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 cached {@link IdToken} without triggering a refresh.
*
* <p>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 cached {@link IdToken}, or {@code null} before the first refresh
*/
public @Nullable IdToken getIdToken() {
return (IdToken) getAccessToken();
}
Expand Down Expand Up @@ -206,6 +247,12 @@ public static Builder newBuilder() {
return new Builder();
}

/**
* Builder for {@link IdTokenCredentials}.
*
* <p>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;
Expand All @@ -217,52 +264,81 @@ protected Builder() {}
/**
* Sets the provider for the ID token.
*
* <p>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) {
this.idTokenProvider = Preconditions.checkNotNull(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;
}

/**
* 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.
* @return the builder object
* <p>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 (ignored by {@code UserCredentials})
* @return this builder
*/
@CanIgnoreReturnValue
public Builder setTargetAudience(@Nullable String targetAudience) {
this.targetAudience = 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.
*
* <p>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.
* @return the builder object
* @param options list of options, or {@code null} or empty if no options are needed
* @return this builder
*/
@CanIgnoreReturnValue
public Builder setOptions(@Nullable List<IdTokenProvider.Option> options) {
this.options = 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<IdTokenProvider.Option> getOptions() {
return this.options;
}

/**
* Builds an {@link IdTokenCredentials} instance from this builder.
*
* <p>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);
Expand Down
Loading
Loading