1717package com .example .iap ;
1818// [START iap_make_request]
1919
20- import com .google .api .client .http .GenericUrl ;
21- import com .google .api .client .http .HttpHeaders ;
2220import com .google .api .client .http .HttpRequest ;
23- import com .google .api .client .http .HttpRequestFactory ;
24- import com .google .api .client .http .HttpResponse ;
21+ import com .google .api .client .http .HttpRequestInitializer ;
2522import com .google .api .client .http .HttpTransport ;
26- import com .google .api .client .http .UrlEncodedContent ;
2723import com .google .api .client .http .javanet .NetHttpTransport ;
28- import com .google .api .client .json .JsonObjectParser ;
29- import com .google .api .client .json .jackson2 .JacksonFactory ;
30- import com .google .api .client .util .GenericData ;
24+ import com .google .auth .http .HttpCredentialsAdapter ;
3125import com .google .auth .oauth2 .GoogleCredentials ;
32- import com .google .auth .oauth2 .ServiceAccountCredentials ;
33- import com .nimbusds .jose .JWSAlgorithm ;
34- import com .nimbusds .jose .JWSHeader ;
35- import com .nimbusds .jose .JWSSigner ;
36- import com .nimbusds .jose .crypto .RSASSASigner ;
37- import com .nimbusds .jwt .JWTClaimsSet ;
38- import com .nimbusds .jwt .SignedJWT ;
26+ import com .google .auth .oauth2 .IdTokenCredentials ;
27+ import com .google .auth .oauth2 .IdTokenProvider ;
3928import java .time .Clock ;
40- import java .time .Instant ;
4129import java .util .Collections ;
42- import java .util .Date ;
4330
4431public class BuildIapRequest {
4532 private static final String IAM_SCOPE = "https://www.googleapis.com/auth/iam" ;
@@ -54,63 +41,14 @@ public class BuildIapRequest {
5441
5542 private BuildIapRequest () {}
5643
57- private static ServiceAccountCredentials getCredentials () throws Exception {
44+ private static IdTokenProvider getIdTokenProvider () throws Exception {
5845 GoogleCredentials credentials =
5946 GoogleCredentials .getApplicationDefault ().createScoped (Collections .singleton (IAM_SCOPE ));
6047 // service account credentials are required to sign the jwt token
61- if (credentials == null || !(credentials instanceof ServiceAccountCredentials )) {
62- throw new Exception ("Google credentials : service accounts credentials expected" );
48+ if (credentials == null || !(credentials instanceof IdTokenProvider )) {
49+ throw new Exception ("Google credentials : credentials that can provide id tokens expected" );
6350 }
64- return (ServiceAccountCredentials ) credentials ;
65- }
66-
67- private static String getSignedJwt (ServiceAccountCredentials credentials , String iapClientId )
68- throws Exception {
69- Instant now = Instant .now (clock );
70- long expirationTime = now .getEpochSecond () + EXPIRATION_TIME_IN_SECONDS ;
71-
72- // generate jwt signed by service account
73- // header must contain algorithm ("alg") and key ID ("kid")
74- JWSHeader jwsHeader =
75- new JWSHeader .Builder (JWSAlgorithm .RS256 ).keyID (credentials .getPrivateKeyId ()).build ();
76-
77- // set required claims
78- JWTClaimsSet claims =
79- new JWTClaimsSet .Builder ()
80- .audience (OAUTH_TOKEN_URI )
81- .issuer (credentials .getClientEmail ())
82- .subject (credentials .getClientEmail ())
83- .issueTime (Date .from (now ))
84- .expirationTime (Date .from (Instant .ofEpochSecond (expirationTime )))
85- .claim ("target_audience" , iapClientId )
86- .build ();
87-
88- // sign using service account private key
89- JWSSigner signer = new RSASSASigner (credentials .getPrivateKey ());
90- SignedJWT signedJwt = new SignedJWT (jwsHeader , claims );
91- signedJwt .sign (signer );
92-
93- return signedJwt .serialize ();
94- }
95-
96- private static String getGoogleIdToken (String jwt ) throws Exception {
97- final GenericData tokenRequest =
98- new GenericData ().set ("grant_type" , JWT_BEARER_TOKEN_GRANT_TYPE ).set ("assertion" , jwt );
99- final UrlEncodedContent content = new UrlEncodedContent (tokenRequest );
100-
101- final HttpRequestFactory requestFactory = httpTransport .createRequestFactory ();
102-
103- final HttpRequest request =
104- requestFactory
105- .buildPostRequest (new GenericUrl (OAUTH_TOKEN_URI ), content )
106- .setParser (new JsonObjectParser (JacksonFactory .getDefaultInstance ()));
107-
108- HttpResponse response ;
109- String idToken = null ;
110- response = request .execute ();
111- GenericData responseData = response .parseAs (GenericData .class );
112- idToken = (String ) responseData .get ("id_token" );
113- return idToken ;
51+ return (IdTokenProvider ) credentials ;
11452 }
11553
11654 /**
@@ -123,31 +61,18 @@ private static String getGoogleIdToken(String jwt) throws Exception {
12361 */
12462 public static HttpRequest buildIapRequest (HttpRequest request , String iapClientId )
12563 throws Exception {
126- // get service account credentials
127- ServiceAccountCredentials credentials = getCredentials ();
128- // get the base url of the request URL
129- String jwt = getSignedJwt (credentials , iapClientId );
130- if (jwt == null ) {
131- throw new Exception (
132- "Unable to create a signed jwt token for : "
133- + iapClientId
134- + "with issuer : "
135- + credentials .getClientEmail ());
136- }
13764
138- String idToken = getGoogleIdToken (jwt );
139- if (idToken == null ) {
140- throw new Exception ("Unable to retrieve open id token" );
141- }
65+ IdTokenProvider idTokenProvider = getIdTokenProvider ();
66+ IdTokenCredentials credentials = IdTokenCredentials .newBuilder ()
67+ .setIdTokenProvider (idTokenProvider )
68+ .setTargetAudience (iapClientId )
69+ .build ();
14270
143- // Create an authorization header with bearer token
144- HttpHeaders httpHeaders = request .getHeaders ().clone ().setAuthorization ("Bearer " + idToken );
71+ HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter (credentials );
14572
146- // create request with jwt authorization header
14773 return httpTransport
148- .createRequestFactory ()
149- .buildRequest (request .getRequestMethod (), request .getUrl (), request .getContent ())
150- .setHeaders (httpHeaders );
74+ .createRequestFactory (httpRequestInitializer )
75+ .buildRequest (request .getRequestMethod (), request .getUrl (), request .getContent ());
15176 }
15277}
15378// [END iap_make_request]
0 commit comments