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 @@ -42,67 +42,88 @@
import org.jspecify.annotations.Nullable;

/**
* IdTokenCredentials provides a Google Issued OpenIdConnect token. <br>
* Use an ID token to access services that require presenting an ID token for authentication such as
* Cloud Functions or Cloud Run.<br>
* The following Credential subclasses support IDTokens: ServiceAccountCredentials,
* ComputeEngineCredentials, ImpersonatedCredentials.
* IdTokenCredentials provides a Google-issued OpenID Connect (OIDC) ID token.
*
* <p>For more information see <br>
* Usage:<br>
* <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}.
*
* <pre>
* <p>For more information, see <a
* href="https://docs.cloud.google.com/docs/authentication/get-id-token">Get an ID token</a>.
*
* <p>Usage:
*
* <pre>{@code
* String credPath = "/path/to/svc_account.json";
* String targetAudience = "https://example.com";
*
* // For Application Default Credentials (as ServiceAccountCredentials)
* // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/svc.json
* GoogleCredentials adcCreds = GoogleCredentials.getApplicationDefault();
* if (!adcCreds instanceof IdTokenProvider) {
* // handle error message
* if (!(adcCreds instanceof IdTokenProvider)) {
* throw new IllegalStateException("Credentials do not support ID tokens.");
* }
*
* IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder()
* .setIdTokenProvider(adcCreds)
* .setTargetAudience(targetAudience).build();
* IdTokenCredentials tokenCredential =
* IdTokenCredentials.newBuilder()
* .setIdTokenProvider((IdTokenProvider) adcCreds)
* .setTargetAudience(targetAudience)
* .build();
*
* // for ServiceAccountCredentials
* ServiceAccountCredentials saCreds = ServiceAccountCredentials.fromStream(new FileInputStream(credPath));
* saCreds = (ServiceAccountCredentials) saCreds.createScoped(Arrays.asList("https://www.googleapis.com/auth/iam"));
* IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder()
* .setIdTokenProvider(saCreds)
* .setTargetAudience(targetAudience).build();
* // For ServiceAccountCredentials
* ServiceAccountCredentials saCreds =
* ServiceAccountCredentials.fromStream(new FileInputStream(credPath));
* saCreds =
* (ServiceAccountCredentials)
* saCreds.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
* IdTokenCredentials saTokenCredential =
* IdTokenCredentials.newBuilder()
* .setIdTokenProvider(saCreds)
* .setTargetAudience(targetAudience)
* .build();
*
* // for ComputeEngineCredentials
* ComputeEngineCredentials caCreds = ComputeEngineCredentials.create();
* IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder()
* .setIdTokenProvider(caCreds)
* .setTargetAudience(targetAudience)
* .setOptions(Arrays.asList(ComputeEngineCredentials.ID_TOKEN_FORMAT_FULL))
* .build();
* // For ComputeEngineCredentials
* ComputeEngineCredentials ceCreds = ComputeEngineCredentials.create();
* IdTokenCredentials ceTokenCredential =
* IdTokenCredentials.newBuilder()
* .setIdTokenProvider(ceCreds)
* .setTargetAudience(targetAudience)
* .setOptions(Arrays.asList(IdTokenProvider.Option.FORMAT_FULL))
* .build();
*
* // for ImpersonatedCredentials
* ImpersonatedCredentials imCreds = ImpersonatedCredentials.create(saCreds,
* "impersonated-account@project.iam.gserviceaccount.com", null,
* Arrays.asList("https://www.googleapis.com/auth/cloud-platform"), 300);
* IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder()
* .setIdTokenProvider(imCreds)
* .setTargetAudience(targetAudience)
* .setOptions(Arrays.asList(ImpersonatedCredentials.INCLUDE_EMAIL))
* .build();
* // For ImpersonatedCredentials
* ImpersonatedCredentials imCreds =
* ImpersonatedCredentials.create(
* saCreds,
* "impersonated-account@project.iam.gserviceaccount.com",
* null,
* Arrays.asList("https://www.googleapis.com/auth/cloud-platform"),
* 300);
* IdTokenCredentials imTokenCredential =
* IdTokenCredentials.newBuilder()
* .setIdTokenProvider(imCreds)
* .setTargetAudience(targetAudience)
* .setOptions(Arrays.asList(IdTokenProvider.Option.INCLUDE_EMAIL))
* .build();
Comment on lines +68 to +108

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In this Javadoc snippet, multiple distinct variables are declared (saTokenCredential, ceTokenCredential, imTokenCredential) but never used, while tokenCredential is declared once at the beginning and then used at the end of the snippet. This can lead to unused variable warnings or compilation errors if a developer copy-pastes the entire block. Reusing a single tokenCredential variable across all examples makes the snippet cleaner, more cohesive, and fully copy-pasteable.

 * IdTokenCredentials tokenCredential;
 *
 * // For Application Default Credentials (as ServiceAccountCredentials)
 * // 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.");
 * }
 *
 * tokenCredential =
 *     IdTokenCredentials.newBuilder()
 *         .setIdTokenProvider((IdTokenProvider) adcCreds)
 *         .setTargetAudience(targetAudience)
 *         .build();
 *
 * // For 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)
 *         .setTargetAudience(targetAudience)
 *         .build();
 *
 * // For ComputeEngineCredentials
 * ComputeEngineCredentials ceCreds = ComputeEngineCredentials.create();
 * tokenCredential =
 *     IdTokenCredentials.newBuilder()
 *         .setIdTokenProvider(ceCreds)
 *         .setTargetAudience(targetAudience)
 *         .setOptions(Arrays.asList(IdTokenProvider.Option.FORMAT_FULL))
 *         .build();
 *
 * // For ImpersonatedCredentials
 * ImpersonatedCredentials imCreds =
 *     ImpersonatedCredentials.create(
 *         saCreds,
 *         "impersonated-account@project.iam.gserviceaccount.com",
 *         null,
 *         Arrays.asList("https://www.googleapis.com/auth/cloud-platform"),
 *         300);
 * tokenCredential =
 *     IdTokenCredentials.newBuilder()
 *         .setIdTokenProvider(imCreds)
 *         .setTargetAudience(targetAudience)
 *         .setOptions(Arrays.asList(IdTokenProvider.Option.INCLUDE_EMAIL))
 *         .build();
References
  1. When calling createScoped on ServiceAccountCredentials, the returned object is of type GoogleCredentials. A cast to ServiceAccountCredentials is required if you need to access subclass-specific methods such as createWithUseJwtAccessWithScope.

*
* // Use the IdTokenCredential in an authorized transport
* // Use the IdTokenCredentials in an authorized transport
* GenericUrl genericUrl = new GenericUrl("https://example.com");
* HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(tokenCredential);
* HttpTransport transport = new NetHttpTransport();
* HttpRequest request = transport.createRequestFactory(adapter).buildGetRequest(genericUrl);
* HttpResponse response = request.execute();
*
* // Print the token, expiration and the audience
* System.out.println(tokenCredential.getIdToken().getTokenValue());
* System.out.println(tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudienceAsList());
* System.out.println(tokenCredential.getIdToken().getJsonWebSignature().getPayload().getExpirationTimeSeconds());
* </pre>
* // Print the token value, expiration, and parsed payload claims
* tokenCredential.refreshIfExpired();
* IdToken idToken = tokenCredential.getIdToken();
* System.out.println(idToken.getTokenValue());
* System.out.println(idToken.getExpirationTime());
* JsonWebSignature jws =
* JsonWebSignature.parse(GsonFactory.getDefaultInstance(), idToken.getTokenValue());
* System.out.println(jws.getPayload().getAudienceAsList());
* System.out.println(jws.getPayload().getExpirationTimeSeconds());
* }</pre>
*/
@NullMarked
public class IdTokenCredentials extends OAuth2Credentials {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@
* ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials
* .fromStream(new FileInputStream(credPath));
* sourceCredentials = (ServiceAccountCredentials) sourceCredentials
* .createScoped(Arrays.asList("https://www.googleapis.com/auth/iam"));
* .createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
*
* ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create(sourceCredentials,
* "impersonated-account@project.iam.gserviceaccount.com", null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
* <p>To create and customize claims, use the builder:
*
* <pre><code>
* Claims claims = Claims.newBuilder()
* JwtClaims claims = JwtClaims.newBuilder()
* .setAudience("https://example.com/some-audience")
* .setIssuer("some-issuer@example.com")
* .setSubject("some-subject@example.com")
Expand Down Expand Up @@ -77,7 +77,7 @@ public static Builder newBuilder() {
}

/**
* Returns a new Claims instance with overridden fields.
* Returns a new {@link JwtClaims} instance with overridden fields.
*
* <p>Any non-null field will overwrite the value from the original claims instance.
*
Expand All @@ -100,8 +100,9 @@ public JwtClaims merge(JwtClaims other) {
/**
* Returns whether or not this set of claims is complete.
*
* <p>Audience, issuer, and subject are required to be set in order to use the claim set for a JWT
* token. An incomplete Claims instance is useful for overriding claims when using {@link
* <p>Audience (or a non-empty {@code scope} additional claim), issuer, and subject are required
* to be set in order to use the claim set for a JWT token. An incomplete {@link JwtClaims}
* instance is useful for overriding claims when using {@link
* ServiceAccountJwtAccessCredentials#jwtWithClaims(JwtClaims)} or {@link
* JwtCredentials#jwtWithClaims(JwtClaims)}.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
* .setIssuer("some-issuer@example.com")
* .setSubject("some-subject@example.com")
* .build();
* Credentials = JwtCredentials.newBuilder()
* Credentials credentials = JwtCredentials.newBuilder()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using the specific type JwtCredentials instead of the generic Credentials is more idiomatic, matches the builder type, and avoids requiring an extra import for com.google.auth.Credentials when developers copy-paste this snippet.

Suggested change
* Credentials credentials = JwtCredentials.newBuilder()
* JwtCredentials credentials = JwtCredentials.newBuilder()

* .setPrivateKey(privateKey)
* .setPrivateKeyId("private-key-id")
* .setJwtClaims(claims)
Expand Down
Loading