IAP samples update by jabubake · Pull Request #808 · GoogleCloudPlatform/java-docs-samples · GitHub
Skip to content
Merged
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
2 changes: 1 addition & 1 deletion iap/README.md
7 changes: 3 additions & 4 deletions iap/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,16 @@
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<!-- [START dependencies] -->
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>0.7.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>4.41.1</version>
</dependency>
<!-- [END dependencies] -->

Expand Down
59 changes: 37 additions & 22 deletions iap/src/main/java/com/example/iap/BuildIapRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.iap;
// [START generate_iap_request]

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
Expand All @@ -26,18 +28,18 @@
import com.google.api.client.util.GenericData;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.io.IOException;
import java.net.URL;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import java.time.Clock;
import java.time.Instant;
import java.util.Collections;
import java.util.Date;

public class BuildIapRequest {
// [START generate_iap_request]
private static final String IAM_SCOPE = "https://www.googleapis.com/auth/iam";
private static final String OAUTH_TOKEN_URI = "https://www.googleapis.com/oauth2/v4/token";
private static final String JWT_BEARER_TOKEN_GRANT_TYPE =
Expand All @@ -60,22 +62,33 @@ private static ServiceAccountCredentials getCredentials() throws Exception {
return (ServiceAccountCredentials) credentials;
}

private static String getSignedJWToken(ServiceAccountCredentials credentials, String iapClientId)
throws IOException {
private static String getSignedJwt(ServiceAccountCredentials credentials, String iapClientId)
throws Exception {
Instant now = Instant.now(clock);
long expirationTime = now.getEpochSecond() + EXPIRATION_TIME_IN_SECONDS;

// generate jwt signed by service account
return Jwts.builder()
.setHeaderParam("kid", credentials.getPrivateKeyId())
.setIssuer(credentials.getClientEmail())
.setAudience(OAUTH_TOKEN_URI)
.setSubject(credentials.getClientEmail())
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(Instant.ofEpochSecond(expirationTime)))
.claim("target_audience", iapClientId)
.signWith(SignatureAlgorithm.RS256, credentials.getPrivateKey())
.compact();
// header must contain algorithm ("alg") and key ID ("kid")
JWSHeader jwsHeader =
new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(credentials.getPrivateKeyId()).build();

// set required claims
JWTClaimsSet claims =
new JWTClaimsSet.Builder()
.audience(OAUTH_TOKEN_URI)
.issuer(credentials.getClientEmail())
.subject(credentials.getClientEmail())
.issueTime(Date.from(now))
.expirationTime(Date.from(Instant.ofEpochSecond(expirationTime)))
.claim("target_audience", iapClientId)
.build();

// sign using service account private key
JWSSigner signer = new RSASSASigner(credentials.getPrivateKey());
SignedJWT signedJwt = new SignedJWT(jwsHeader, claims);
signedJwt.sign(signer);

return signedJwt.serialize();
}

private static String getGoogleIdToken(String jwt) throws Exception {
Expand All @@ -100,16 +113,18 @@ private static String getGoogleIdToken(String jwt) throws Exception {

/**
* Clone request and add an IAP Bearer Authorization header with signed JWT token.
*
* @param request Request to add authorization header
* @param iapClientId OAuth 2.0 client ID for IAP protected resource
* @return Clone of request with Bearer style authorization header with signed jwt token.
* @throws Exception
* @throws Exception exception creating signed JWT
*/
public static HttpRequest buildIAPRequest(HttpRequest request, String iapClientId) throws Exception {
public static HttpRequest buildIapRequest(HttpRequest request, String iapClientId)
throws Exception {
// get service account credentials
ServiceAccountCredentials credentials = getCredentials();
// get the base url of the request URL
String jwt = getSignedJWToken(credentials, iapClientId);
String jwt = getSignedJwt(credentials, iapClientId);
if (jwt == null) {
throw new Exception(
"Unable to create a signed jwt token for : "
Expand All @@ -132,5 +147,5 @@ public static HttpRequest buildIAPRequest(HttpRequest request, String iapClientI
.buildRequest(request.getRequestMethod(), request.getUrl(), request.getContent())
.setHeaders(httpHeaders);
}
// [END generate_iap_request]
}
// [END generate_iap_request]
223 changes: 91 additions & 132 deletions iap/src/main/java/com/example/iap/VerifyIapRequestHeader.java
Loading