Skip to content
Closed
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,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.
*
* <p>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.
*
* <p>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}.
*
* <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 +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
* <p>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
* <p>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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <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 {@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.
*
* <p>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.
*
* <p>For more information, see <a
* href="https://docs.cloud.google.com/docs/authentication/get-id-token">Get an ID token</a>.
Expand Down Expand Up @@ -127,6 +141,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 +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.
*
* <p>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();
}
Expand Down Expand Up @@ -217,6 +252,8 @@ 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
*/
Expand All @@ -226,15 +263,23 @@ 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;
}

/**
* 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.
* <p>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
Expand All @@ -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.
*
* <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.
* @param options list of options, or {@code null} or empty if no options are needed
* @return the builder object
*/
@CanIgnoreReturnValue
Expand All @@ -259,10 +311,23 @@ public Builder setOptions(@Nullable List<IdTokenProvider.Option> 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
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>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.
*
* <p>For details on getting ID tokens in different environments, see <a
* href="https://docs.cloud.google.com/docs/authentication/get-id-token">Get an ID token</a>.
*
* @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.
*
* <p><b>ComputeEngineCredentials</b>
* <p>Each {@link IdTokenProvider} honors only the options it supports and ignores all others:
*
* <ul>
* <li>FORMAT_FULL
* <li>LICENSES_TRUE
* <li>DISABLE_BOUND_ID_TOKEN
* </ul>
*
* <br>
* <b>ImpersonatedCredential</b>
*
* <ul>
* <li>INCLUDE_EMAIL
* <li>{@link ComputeEngineCredentials}: {@link #FORMAT_FULL}, {@link #LICENSES_TRUE}, and
* {@link #DISABLE_BOUND_ID_TOKEN}
* <li>{@link ImpersonatedCredentials}: {@link #INCLUDE_EMAIL}
* <li>{@link ServiceAccountCredentials} and {@link UserCredentials}: ignore all options
* </ul>
*/
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.
Expand Down Expand Up @@ -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.
*
* <p>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<Option> options)
throws IOException;
Expand Down
Loading