Skip to content

Commit

Permalink
IAP sample update : new JWT header (#757)
Browse files Browse the repository at this point in the history
  • Loading branch information
jabubake authored Jul 17, 2017
1 parent bd564e8 commit a77fee7
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
@SuppressWarnings("serial")
public class JwtServlet extends HttpServlet {

private static final String IAP_JWT_HEADER = "x-goog-authenticated-user-jwt";
private static final String IAP_JWT_HEADER = "x-goog-iap-jwt-assertion";

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Expand Down
19 changes: 17 additions & 2 deletions iap/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,25 @@ verify the JWT token in an incoming request to an IAP protected resource.
## Testing
- Deploy the [demo app engine application](../appengine/iap/README.md). This application will return the JWT token to an authorized incoming request.
It will be used to test both the authorization of an incoming request to an IAP protected resource and the JWT token returned from IAP.

- [Enable](https://cloud.google.com/iap/docs/app-engine-quickstart) Identity-Aware Proxy on the App Engine app.

- Add the service account email to the Identity-Aware Proxy access list for the project.
- Set the environment variable `IAP_PROTECTED_URL` to point to `https://your-project-id.appspot.com`
- Set the environment variable `IAP_CLIENT_ID` to point to the [OAuth 2.0 Client ID](https://console.cloud.google.com/apis/credentials) of your IAP protected App Engine Application.

- Set the following environment variables to test sending a request to an IAP protected resource:
- `IAP_PROTECTED_URL` : URL of your IAP protected resource . eg. `https://your-project-id.appspot.com`

- `IAP_CLIENT_ID` to point to the [OAuth 2.0 Client ID](https://console.cloud.google.com/apis/credentials) of your IAP protected App Engine Application.

- Set the following environment variables to test verifying a JWT issued for an App Engine protected application:
- `GOOGLE_CLOUD_PROJECT`: Google Cloud Project ID

- `IAP_PROJECT_NUMBER` : [Project number](https://console.cloud.google.com/home/dashboard) of the IAP protected resource.
Also available via `gcloud` using:
```
gcloud projects describe PROJECT_ID
```

- Run the integration test:
```
mvn -Dtest=com.example.iap.BuildAndVerifyIapRequestIT verify
Expand Down
35 changes: 22 additions & 13 deletions iap/src/main/java/com/example/iap/VerifyIapRequestHeader.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
Expand Down Expand Up @@ -100,33 +99,43 @@ 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();
// Verify jwt tokens addressed to IAP protected resources on App Engine.
// The project *number* for your Google Cloud project available via 'gcloud projects describe $PROJECT_ID'
// or in the Project Info card in Cloud Console.
// projectId is The project *ID* for your Google Cloud Project.
Jwt verifyJWTTokenForAppEngine(HttpRequest request, long projectNumber, String projectId) 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(projectNumber),
projectId));
}

Jwt verifyJWTToken(HttpRequest request) throws Exception {
Jwt verifyJWTTokenForComputeEngine(HttpRequest request, long projectNumber, long backendServiceId) 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(projectNumber),
Long.toUnsignedString(backendServiceId)));
}

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
14 changes: 12 additions & 2 deletions iap/src/test/java/com/example/iap/BuildAndVerifyIapRequestIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import static org.junit.Assert.assertNotNull;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
Expand All @@ -35,6 +36,8 @@ public class BuildAndVerifyIapRequestIT {

private String iapProtectedUrl = System.getenv("IAP_PROTECTED_URL");
private String iapClientId = System.getenv("IAP_CLIENT_ID");
private Long projectNumber = Long.parseLong(System.getenv("IAP_PROJECT_NUMBER"));
private String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
private HttpTransport httpTransport = new NetHttpTransport();
private VerifyIapRequestHeader verifyIapRequestHeader = new VerifyIapRequestHeader();

Expand Down Expand Up @@ -68,8 +71,15 @@ public void testGenerateAndVerifyIapRequestIsSuccessful() throws Exception {
String[] split = headerWithtoken.split(":");
assertNotNull(split);
assertEquals(split.length, 2);
assertEquals(split[0].trim(), "x-goog-authenticated-user-jwt");
Jwt decodedJWT = verifyIapRequestHeader.verifyJWTToken(split[1].trim(), iapProtectedUrl);
assertEquals(split[0].trim(), "x-goog-iap-jwt-assertion");

String jwtToken = split[1].trim();
HttpRequest verifyJwtRequest = httpTransport
.createRequestFactory()
.buildGetRequest(new GenericUrl(iapProtectedUrl)).setHeaders(
new HttpHeaders().set("x-goog-iap-jwt-assertion", jwtToken));
Jwt decodedJWT = verifyIapRequestHeader.verifyJWTTokenForAppEngine(
verifyJwtRequest, projectNumber, projectId);
assertNotNull(decodedJWT);
}
}
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
<module>compute/sendgrid</module>
<module>datastore</module>
<module>datastore/cloud-client</module>
<module>iap</module>
<module>kms</module>
<module>language/analysis</module>
<module>language/cloud-client</module>
Expand Down

0 comments on commit a77fee7

Please sign in to comment.