17
17
package com .example .iap ;
18
18
// [START iap_make_request]
19
19
20
- import com .google .api .client .http .GenericUrl ;
21
- import com .google .api .client .http .HttpHeaders ;
22
20
import 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 ;
25
22
import com .google .api .client .http .HttpTransport ;
26
- import com .google .api .client .http .UrlEncodedContent ;
27
23
import 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 ;
31
25
import 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 ;
39
28
import java .time .Clock ;
40
- import java .time .Instant ;
41
29
import java .util .Collections ;
42
- import java .util .Date ;
43
30
44
31
public class BuildIapRequest {
45
32
private static final String IAM_SCOPE = "https://www.googleapis.com/auth/iam" ;
@@ -54,63 +41,14 @@ public class BuildIapRequest {
54
41
55
42
private BuildIapRequest () {}
56
43
57
- private static ServiceAccountCredentials getCredentials () throws Exception {
44
+ private static IdTokenProvider getIdTokenProvider () throws Exception {
58
45
GoogleCredentials credentials =
59
46
GoogleCredentials .getApplicationDefault ().createScoped (Collections .singleton (IAM_SCOPE ));
60
47
// 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" );
63
50
}
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 ;
114
52
}
115
53
116
54
/**
@@ -123,31 +61,18 @@ private static String getGoogleIdToken(String jwt) throws Exception {
123
61
*/
124
62
public static HttpRequest buildIapRequest (HttpRequest request , String iapClientId )
125
63
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
- }
137
64
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 ();
142
70
143
- // Create an authorization header with bearer token
144
- HttpHeaders httpHeaders = request .getHeaders ().clone ().setAuthorization ("Bearer " + idToken );
71
+ HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter (credentials );
145
72
146
- // create request with jwt authorization header
147
73
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 ());
151
76
}
152
77
}
153
78
// [END iap_make_request]
0 commit comments