Skip to content
Open
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 @@ -44,17 +44,38 @@ public static void main(String[] args) {
verifyGoogleIdToken(idToken, targetAudience, jwkUrl);
}

// Verifies the obtained Google id token. This is done at the receiving end of the OIDC endpoint.
// The most common use case for verifying the ID token is when you are protecting
// your own APIs with IAP. Google services already verify credentials as a platform,
// so verifying ID tokens before making Google API calls is usually unnecessary.
/**
* Verifies a Google-signed OpenID Connect (OIDC) ID token at the receiving service.
*
* <p>The most common use case is protecting your own APIs (for example, behind Identity-Aware
* Proxy). Google Cloud APIs already verify credentials on the server side, so verifying ID tokens
* before calling Google APIs is usually unnecessary.
*
* <p>{@link TokenVerifier#verify(String)} checks the token signature, signing algorithm ({@code
* RS256} or {@code ES256}), expiration ({@code exp}), and expected audience ({@code aud}).
*
* @param idToken the encoded Google-signed OIDC ID token (JWT string) received from the caller
* @param audience the expected {@code aud} claim identifying your service or application (for
* example, your service URL or OAuth client ID). Verification fails if the token's {@code
* aud} claim does not match, preventing tokens issued for another service from being accepted
* @param jwkUrl the HTTPS URL of the JSON Web Key Set (JWKS) endpoint publishing the public keys
* used to verify the token's signature (matched by the JWT header's {@code kid}). Passed to
* {@link TokenVerifier.Builder#setCertificatesLocation(String)}. Optional (may be {@code
* null}) for standard Google-signed tokens. When omitted or {@code null}, {@link
* TokenVerifier} 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} (IAP) tokens. Provide an explicit URL to pin a certificate endpoint or verify tokens
* signed with keys hosted elsewhere
*/
public static void verifyGoogleIdToken(String idToken, String audience, String jwkUrl) {
// Initialize the Token verifier and set the audience.
TokenVerifier tokenVerifier =
TokenVerifier.newBuilder()
.setAudience(audience)
// Optional, when verifying a Google ID token, the jwk url is set by default.
.setIssuer(jwkUrl)
// See:
// https://docs.cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.TokenVerifier.Builder#com_google_auth_oauth2_TokenVerifier_Builder_setCertificatesLocation_java_lang_String_
.setCertificatesLocation(jwkUrl)
.build();

try {
Expand Down
Loading