Skip to content

Update JWT validation to use new JWT header #756

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
32 changes: 19 additions & 13 deletions iap/src/main/java/com/example/iap/VerifyIapRequestHeader.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,33 +100,39 @@ private Key resolveSigningKey(JwsHeader header) {
}
};

private static String getBaseUrl(URL url) throws Exception {
String urlFilePath = url.getFile();
int pathDelim = urlFilePath.lastIndexOf('/');
String path = (pathDelim > 0) ? urlFilePath.substring(0, pathDelim) : "";
return (url.getProtocol() + "://" + url.getHost() + path).trim();
Jwt verifyJWTTokenForAppEngine(HttpRequest request, long project_number, String project_id) throws Exception {
// Check for iap jwt header in incoming request
String jwtToken =
request.getHeaders().getFirstHeaderStringValue("x-goog-iap-jwt-assertion");
if (jwtToken == null) {
return null;
}
return verifyJWTToken(jwtToken, String.format("/projects/%s/apps/%s",
Long.toUnsignedString(project_number),
project_id));
}

Jwt verifyJWTToken(HttpRequest request) throws Exception {
Jwt verifyJWTTokenForComputeEngine(HttpRequest request, long project_number, long backend_service_id) throws Exception {
// Check for iap jwt header in incoming request
String jwtToken =
request.getHeaders().getFirstHeaderStringValue("x-goog-authenticated-user-jwt");
request.getHeaders().getFirstHeaderStringValue("x-goog-iap-jwt-assertion");
if (jwtToken == null) {
return null;
}
String baseUrl = getBaseUrl(request.getUrl().toURL());
return verifyJWTToken(jwtToken, baseUrl);
return verifyJWTToken(jwtToken, String.format("/projects/%s/global/backendServices/%s",
Long.toUnsignedString(project_number),
Long.toUnsignedString(backend_service_id)));
}

Jwt verifyJWTToken(String jwtToken, String baseUrl) throws Exception {
Jwt verifyJWTToken(String jwtToken, String expectedAudience) throws Exception {
// Time constraints are automatically checked, use setAllowedClockSkewSeconds
// to specify a leeway window
// The token was issued in a past date "iat" < TODAY
// The token hasn't expired yet "exp" > TODAY
Jwt jwt =
Jwts.parser()
.setSigningKeyResolver(resolver)
.requireAudience(baseUrl)
.requireAudience(expectedAudience)
.requireIssuer(IAP_ISSUER_URL)
.parse(jwtToken);
DefaultClaims claims = (DefaultClaims) jwt.getBody();
Expand Down