-
Notifications
You must be signed in to change notification settings - Fork 87
/
Federation.java
810 lines (643 loc) · 25.2 KB
/
Federation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
/*
* Copyright (C) 2022 Authlete, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.authlete.jaxrs.server.federation;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.proc.BadJOSEException;
import com.nimbusds.jwt.JWT;
import com.nimbusds.oauth2.sdk.AbstractRequest;
import com.nimbusds.oauth2.sdk.AuthorizationCode;
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant;
import com.nimbusds.oauth2.sdk.AuthorizationGrant;
import com.nimbusds.oauth2.sdk.ErrorObject;
import com.nimbusds.oauth2.sdk.ErrorResponse;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.ResponseType;
import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.oauth2.sdk.TokenRequest;
import com.nimbusds.oauth2.sdk.TokenResponse;
import com.nimbusds.oauth2.sdk.auth.ClientAuthentication;
import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic;
import com.nimbusds.oauth2.sdk.auth.Secret;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import com.nimbusds.oauth2.sdk.id.ClientID;
import com.nimbusds.oauth2.sdk.id.Issuer;
import com.nimbusds.oauth2.sdk.id.State;
import com.nimbusds.oauth2.sdk.id.Subject;
import com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod;
import com.nimbusds.oauth2.sdk.pkce.CodeVerifier;
import com.nimbusds.oauth2.sdk.token.AccessToken;
import com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse;
import com.nimbusds.openid.connect.sdk.AuthenticationRequest;
import com.nimbusds.openid.connect.sdk.AuthenticationResponse;
import com.nimbusds.openid.connect.sdk.AuthenticationResponseParser;
import com.nimbusds.openid.connect.sdk.OIDCScopeValue;
import com.nimbusds.openid.connect.sdk.OIDCTokenResponse;
import com.nimbusds.openid.connect.sdk.OIDCTokenResponseParser;
import com.nimbusds.openid.connect.sdk.UserInfoRequest;
import com.nimbusds.openid.connect.sdk.UserInfoResponse;
import com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet;
import com.nimbusds.openid.connect.sdk.claims.UserInfo;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderConfigurationRequest;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator;
/**
* Utility for ID federation.
*
* <p>
* This utility class provides public methods for ID federation. The discovery
* document and the JWK set document of the OpenID Provider will be cached
* in an instance of this class.
* </p>
*
* @see FederationConfig
*/
public class Federation
{
private interface ResponseParser<T>
{
T parse(HTTPResponse response) throws ParseException;
}
private static final boolean REQUIRED = true;
private static final boolean OPTIONAL = false;
private final FederationConfig config;
private final Logger logger;
private OIDCProviderMetadata serverMetadata;
private IDTokenValidator idTokenValidator;
public Federation(FederationConfig config)
{
this.config = config;
this.logger = LoggerFactory.getLogger(getClass());
}
//------------------------------------------------------------
// Federation Configuration
//------------------------------------------------------------
public FederationConfig getConfiguration()
{
return config;
}
private <T> T fromFederationConfig(
String path, boolean required,
Function<FederationConfig, T> func) throws IOException
{
T value = null;
try
{
value = func.apply(config);
}
catch (Exception e)
{
}
if (value == null && required)
{
throw ioexception("''{0}'' is not found in the federation configuration.", path);
}
return value;
}
private Issuer issuer() throws IOException
{
String value = fromFederationConfig(
"server/issuer", REQUIRED,
conf -> conf.getServer().getIssuer());
return new Issuer(value);
}
private ClientID clientId() throws IOException
{
String value = fromFederationConfig(
"client/clientId", REQUIRED,
conf -> conf.getClient().getClientId());
return new ClientID(value);
}
private Secret clientSecret() throws IOException
{
String value = fromFederationConfig(
"client/clientSecret", OPTIONAL,
conf -> conf.getClient().getClientSecret());
if (value == null)
{
return null;
}
return new Secret(value);
}
private URI redirectUri() throws IOException
{
String value = fromFederationConfig(
"client/redirectUri", REQUIRED,
conf -> conf.getClient().getRedirectUri());
try
{
return new URI(value);
}
catch (URISyntaxException e)
{
throw ioexception(e, "The value of ''client/redirectUri'' is malformed: {0}", value);
}
}
private JWSAlgorithm idTokenSignedResponseAlg() throws IOException
{
String value = fromFederationConfig(
"client/idTokenSignedResponseAlg", OPTIONAL,
conf -> conf.getClient().getIdTokenSignedResponseAlg());
if (value == null)
{
return null;
}
return JWSAlgorithm.parse(value);
}
//------------------------------------------------------------
// Server Metadata
//------------------------------------------------------------
private OIDCProviderMetadata getServerMetadata() throws IOException
{
// If the server metadata is not cached.
if (serverMetadata == null)
{
// Fetch the server metadata from the discovery endpoint.
serverMetadata = fetchServerMetadata();
}
return serverMetadata;
}
private OIDCProviderMetadata fetchServerMetadata() throws IOException
{
// The issuer identifier of the OpenID provider.
Issuer issuer = issuer();
// Prepare a request to the discovery endpoint.
OIDCProviderConfigurationRequest request =
new OIDCProviderConfigurationRequest(issuer);
// Send the request and receive a response.
HTTPResponse response = sendRequest(request);
// Parse the response.
OIDCProviderMetadata metadata = parseResponse(request, response,
res -> OIDCProviderMetadata.parse(res.getContentAsJSONObject()));
// Validate the discovery document.
validateDiscoveryDocument(issuer, metadata);
return metadata;
}
private void validateDiscoveryDocument(
Issuer issuer, OIDCProviderMetadata metadata) throws IOException
{
if (!issuer.equals(metadata.getIssuer()))
{
// 'issuer' in the discovery document is wrong.
throw ioexception(
"''issuer'' in the discovery document is wrong: expected={0}, actual={1}",
issuer, metadata.getIssuer());
}
}
private <T> T fromServerMetadata(
String path, boolean required,
Function<OIDCProviderMetadata, T> func) throws IOException
{
OIDCProviderMetadata metadata;
try
{
// Get the server metadata.
metadata = getServerMetadata();
}
catch (IOException e)
{
throw e;
}
T value = null;
try
{
value = func.apply(metadata);
}
catch (Exception e)
{
}
if (value == null && required)
{
throw ioexception("''{0}'' is not found in the server metadata.", path);
}
return value;
}
private URI authorizationEndpoint() throws IOException
{
return fromServerMetadata(
"authorization_endpoint", REQUIRED,
metadata -> metadata.getAuthorizationEndpointURI());
}
private URI tokenEndpoint() throws IOException
{
return fromServerMetadata(
"token_endpoint", REQUIRED,
metadata -> metadata.getTokenEndpointURI());
}
private URI userInfoEndpoint() throws IOException
{
return fromServerMetadata(
"userinfo_endpoint", REQUIRED,
metadata -> metadata.getUserInfoEndpointURI());
}
private URI jwksUri() throws IOException
{
return fromServerMetadata(
"jwks_uri", REQUIRED,
metadata -> metadata.getJWKSetURI());
}
private Boolean authorizationResponseIssParameterSupported() throws IOException
{
String key = "authorization_response_iss_parameter_supported";
Object value = fromServerMetadata(
key, OPTIONAL, metadata -> metadata.getCustomParameter(key));
if (value == null)
{
return null;
}
return Boolean.parseBoolean(value.toString());
}
//------------------------------------------------------------
// Common Methods
//------------------------------------------------------------
private HTTPResponse sendRequest(AbstractRequest request) throws IOException
{
try
{
// Send the request to the endpoint.
return request.toHTTPRequest().send();
}
catch (IOException e)
{
// The request to the endpoint failed.
throw ioexception(e, "The request to ''{0}'' failed: {1}",
request.getEndpointURI(), e.getMessage());
}
}
private <T> T parseResponse(
AbstractRequest request, HTTPResponse response, ResponseParser<T> func) throws IOException
{
try
{
// Parse the response.
return func.parse(response);
}
catch (ParseException e)
{
// Failed to parse the response.
throw ioexception(e, "Failed to parse the response from ''{0}'': {1}",
request.getEndpointURI(), e.getMessage());
}
}
private IOException processErrorResponse(URI endpoint, ErrorResponse response)
{
ErrorObject err = response.getErrorObject();
// Log the error and create an IOException.
return ioexception(
"The response from ''{0}'' indicates an error: error={1}, error_description={2}",
endpoint, err.getCode(), err.getDescription());
}
private IOException ioexception(String pattern, Object... arguments)
{
return ioexception((Throwable)null, pattern, arguments);
}
private IOException ioexception(Throwable cause, String pattern, Object... arguments)
{
String message = MessageFormat.format(pattern, arguments);
if (cause != null)
{
logger.error(message, cause);
return new IOException(message, cause);
}
else
{
logger.error(message);
return new IOException(message);
}
}
//------------------------------------------------------------
// Authentication Request
//------------------------------------------------------------
private AuthenticationRequest buildAuthenticationRequest(
State state, CodeVerifier verifier, CodeChallengeMethod method) throws IOException
{
// The authorization endpoint of the OpenID provider.
URI endpoint = authorizationEndpoint();
// response_type
ResponseType responseType = new ResponseType("code");
// scope
Scope scope = buildAuthenticationRequestScope();
// client_id (from federation configuration)
ClientID clientId = clientId();
// redirect_uri (from federation configuration)
URI redirectUri = redirectUri();
// Start to build an authentication request.
AuthenticationRequest.Builder builder =
new AuthenticationRequest.Builder(responseType, scope, clientId, redirectUri)
.endpointURI(endpoint)
;
// state
if (state != null)
{
builder.state(state);
}
// nonce
//
// Optional unless "response_type" includes "id_token".
// See OIDC Core 1.0 Section 3.1.2.1 & Section 3.2.2.1.
//
// But in the Financial-grade API context, "nonce" is mandatory
// when "scope" includes "openid". "response_type" does not matter.
// See FAPI 1.0 Baseline Section 5.2.2.2.
// code_challenge & code_challenge_method
if (verifier != null && method != null)
{
// code_challenge is computed from the verifier and the method.
builder.codeChallenge(verifier, method);
}
return builder.build();
}
private static Scope buildAuthenticationRequestScope()
{
return new Scope(
OIDCScopeValue.ADDRESS,
OIDCScopeValue.EMAIL,
OIDCScopeValue.OPENID,
OIDCScopeValue.PHONE,
OIDCScopeValue.PROFILE
);
}
//------------------------------------------------------------
// Authentication Response
//------------------------------------------------------------
private AuthorizationCode extractAuthorizationCode(
URI response, State state) throws IOException
{
AuthenticationResponse authenticationResponse;
try
{
// Parse the authentication response.
authenticationResponse = AuthenticationResponseParser.parse(response);
}
catch (ParseException e)
{
throw ioexception(e, "Failed to parse the response from ''{0}'': {1}",
authorizationEndpoint(), e.getMessage());
}
// Validate the authentication response.
validateAuthenticationResponse(authenticationResponse, state);
// Extract the authorization code from the response.
return authenticationResponse.toSuccessResponse().getAuthorizationCode();
}
private void validateAuthenticationResponse(
AuthenticationResponse response, State state) throws IOException
{
// If the 'state' included in the authentication response is
// different from the expected state.
if (state != null && !state.equals(response.getState()))
{
throw ioexception("Unexpected authentication response.");
}
// If "authorization_response_iss_parameter_supported" is true.
if (authorizationResponseIssParameterSupported() == Boolean.TRUE)
{
// TODO
// Confirm that the "iss" response parameter is identical to
// the issuer identifier in the discovery document.
// See "OAuth 2.0 Authorization Server Issuer Identification".
}
// If the authentication response indicates an error.
if (response instanceof AuthenticationErrorResponse)
{
// Process the error response.
throw processErrorResponse(
authorizationEndpoint(), response.toErrorResponse());
}
}
//------------------------------------------------------------
// Token Request
//------------------------------------------------------------
private OIDCTokenResponse makeTokenRequest(
AuthorizationCode code, CodeVerifier verifier) throws IOException
{
// Prepare a token request.
TokenRequest request = buildTokenRequest(code, verifier);
// Send the request and receive a response.
HTTPResponse response = sendRequest(request);
// Parse the response.
TokenResponse tokenResponse = parseResponse(request, response,
res -> OIDCTokenResponseParser.parse(res));
// If the token response indicates an error.
if (!tokenResponse.indicatesSuccess())
{
// Process the error response.
throw processErrorResponse(
request.getEndpointURI(), tokenResponse.toErrorResponse());
}
return (OIDCTokenResponse)tokenResponse.toSuccessResponse();
}
private TokenRequest buildTokenRequest(
AuthorizationCode code, CodeVerifier verifier) throws IOException
{
// Client credentials from the federation configuration.
// The client secret may be null.
ClientID clientId = clientId();
Secret clientSecret = clientSecret();
// grant_type=authorization_code
//
// Mandatory, specifying "authorization code grant".
//
// code
//
// Mandatory in the case of grant_type=authorization_code.
//
// redirect_uri
//
// Mandatory when the authorization request included "redirect_uri".
//
// code_verifier
//
// Mandatory when the authorization request included "code_challenge".
//
AuthorizationGrant grant = new AuthorizationCodeGrant(code, redirectUri(), verifier);
// The token endpoint of the OpenID provider.
URI endpoint = tokenEndpoint();
if (clientSecret != null)
{
// Client authentication at the token endpoint, assuming that
// the endpoint supports "client_secret_basic.
ClientAuthentication clientAuth = new ClientSecretBasic(clientId, clientSecret);
// A token request with client authentication.
return new TokenRequest(endpoint, clientAuth, grant);
}
else
{
// A token request without client authentication.
return new TokenRequest(endpoint, clientId, grant);
}
}
//------------------------------------------------------------
// ID Token Validation
//------------------------------------------------------------
private IDTokenValidator getIdTokenValidator() throws IOException
{
// If an ID token validator is not cached.
if (idTokenValidator == null)
{
// Create an ID token validator.
idTokenValidator = createIdTokenValidator();
}
return idTokenValidator;
}
private IDTokenValidator createIdTokenValidator() throws IOException
{
// id_token_signed_response_alg from the federation configuration.
JWSAlgorithm alg = idTokenSignedResponseAlg();
if (alg == null)
{
alg = JWSAlgorithm.RS256;
}
// jwks_uri from the server metadata.
URL jwksLocation = jwksUri().toURL();
// From "How to validate an OpenID Connect ID token"
// https://connect2id.com/blog/how-to-validate-an-openid-connect-id-token
//
// This ID token validator will automatically download the JWK set
// from the IdP and cache the keys to speed up processing. OpenID
// Providers may rotate keys (Google does it once per day), which
// will be detected by the validator, so you don't have to worry
// about this.
//
return new IDTokenValidator(issuer(), clientId(), alg, jwksLocation);
}
private IDTokenClaimsSet validateIdToken(JWT idToken) throws IOException
{
// ID token validator
IDTokenValidator validator = getIdTokenValidator();
try
{
// Validate the ID token.
return validator.validate(idToken, null);
}
catch (BadJOSEException e)
{
// Invalid signature or claims (iss, aud, exp...)
throw ioexception(e, "The ID token issued from ''{0}'' is invalid: {1}",
issuer(), e.getMessage());
}
catch (JOSEException e)
{
// Internal processing exception
throw ioexception(e, "Failed to validate the ID token issued from ''{0}'': {1}",
issuer(), e.getMessage());
}
}
//------------------------------------------------------------
// UserInfo Request
//------------------------------------------------------------
private UserInfo makeUserInfoRequest(AccessToken accessToken) throws IOException
{
// Prepare a userinfo request.
UserInfoRequest request = new UserInfoRequest(userInfoEndpoint(), accessToken);
// Send the request and receive a response.
HTTPResponse response = sendRequest(request);
// Parse the response.
UserInfoResponse userInfoResponse = parseResponse(request, response,
res -> UserInfoResponse.parse(response));
// If the userinfo response indicates an error.
if (!userInfoResponse.indicatesSuccess())
{
// Process the error response.
throw processErrorResponse(
request.getEndpointURI(), userInfoResponse.toErrorResponse());
}
// Extract the user information from the response.
return userInfoResponse.toSuccessResponse().getUserInfo();
}
private void validateUserInfo(UserInfo userInfo, Subject expectedSubject) throws IOException
{
// OpenID Connect Core 1.0, 5.3.2. Successful UserInfo Response
//
// NOTE: Due to the possibility of token substitution attacks
// (see Section 16.11), the UserInfo Response is not guaranteed
// to be about the End-User identified by the sub (subject)
// element of the ID Token. The sub Claim in the UserInfo
// Response MUST be verified to exactly match the sub Claim in
// the ID Token; if they do not match, the UserInfo Response
// values MUST NOT be used.
// If the subject in the ID token does not match the subject in
// the userinfo response.
if (!expectedSubject.equals(userInfo.getSubject()))
{
throw ioexception(
"The subject in the ID token does not match the subject in the userinfo response.");
}
}
//------------------------------------------------------------
// Federation Flow
//------------------------------------------------------------
/**
* Create an authentication request that is to be sent to the authorization
* endpoint of the OpenID Provider.
*/
public URI createFederationRequest(
String state, String codeVerifier) throws IOException
{
// state
State st = (state != null) ? new State(state) : null;
// Code verifier that is to be used to calculate code_challenge.
CodeVerifier verifier = (codeVerifier != null)
? new CodeVerifier(codeVerifier) : null;
// code_challenge_method
CodeChallengeMethod method = (verifier != null)
? CodeChallengeMethod.S256 : null;
// Create an authentication request that is to be sent to
// the authorization endpoint.
AuthenticationRequest request =
buildAuthenticationRequest(st, verifier, method);
return request.toURI();
}
/**
* Process the authentication response from the authorization endpoint of
* the OpenID Provider and retrieve user information from the userinfo
* endpoint of the OpenID Provider.
*/
public UserInfo processFederationResponse(
URI authenticationResponse, String state, String codeVerifier) throws IOException
{
// state
State st = (state != null) ? new State(state) : null;
// code_verifier
CodeVerifier verifier = (codeVerifier != null)
? new CodeVerifier(codeVerifier) : null;
// Extract the authorization code from the authentication response.
AuthorizationCode authorizationCode =
extractAuthorizationCode(authenticationResponse, st);
// Send a token request to the token endpoint and receive a response.
OIDCTokenResponse tokenResponse =
makeTokenRequest(authorizationCode, verifier);
// ID token issued from the token endpoint.
JWT idToken = tokenResponse.getOIDCTokens().getIDToken();
// Validate the ID token.
IDTokenClaimsSet idTokenClaims = validateIdToken(idToken);
// Access token issued from the token endpoint.
AccessToken accessToken = tokenResponse.getOIDCTokens().getAccessToken();
// Send a request to the userinfo endpoint and receive a response.
UserInfo userInfo = makeUserInfoRequest(accessToken);
// Validate the userinfo.
validateUserInfo(userInfo, idTokenClaims.getSubject());
// User information obtained from the OpenID Provider.
return userInfo;
}
}