-
Notifications
You must be signed in to change notification settings - Fork 824
/
UaaTokenServices.java
1207 lines (1034 loc) · 54.5 KB
/
UaaTokenServices.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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Cloud Foundry
* Copyright (c) [2009-2016] Pivotal Software, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product includes a number of subcomponents with
* separate copyright notices and license terms. Your use of these
* subcomponents is subject to the terms and conditions of the
* subcomponent's license, as noted in the LICENSE file.
*******************************************************************************/
package org.cloudfoundry.identity.uaa.oauth;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cloudfoundry.identity.uaa.approval.Approval;
import org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus;
import org.cloudfoundry.identity.uaa.approval.ApprovalStore;
import org.cloudfoundry.identity.uaa.audit.event.TokenIssuedEvent;
import org.cloudfoundry.identity.uaa.authentication.Origin;
import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication;
import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal;
import org.cloudfoundry.identity.uaa.oauth.jwt.Jwt;
import org.cloudfoundry.identity.uaa.oauth.jwt.JwtHelper;
import org.cloudfoundry.identity.uaa.oauth.openid.IdTokenCreationException;
import org.cloudfoundry.identity.uaa.oauth.openid.IdTokenCreator;
import org.cloudfoundry.identity.uaa.oauth.openid.UserAuthenticationData;
import org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants;
import org.cloudfoundry.identity.uaa.oauth.token.CompositeAccessToken;
import org.cloudfoundry.identity.uaa.oauth.token.RevocableToken;
import org.cloudfoundry.identity.uaa.oauth.token.RevocableTokenProvisioning;
import org.cloudfoundry.identity.uaa.oauth.token.TokenConstants;
import org.cloudfoundry.identity.uaa.provider.oauth.XOAuthUserAuthority;
import org.cloudfoundry.identity.uaa.user.UaaAuthority;
import org.cloudfoundry.identity.uaa.user.UaaUser;
import org.cloudfoundry.identity.uaa.user.UaaUserDatabase;
import org.cloudfoundry.identity.uaa.util.JsonUtils;
import org.cloudfoundry.identity.uaa.util.TokenValidation;
import org.cloudfoundry.identity.uaa.util.UaaTokenUtils;
import org.cloudfoundry.identity.uaa.zone.ClientServicesExtension;
import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder;
import org.cloudfoundry.identity.uaa.zone.TokenPolicy;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.Optional.ofNullable;
import static org.cloudfoundry.identity.uaa.oauth.client.ClientConstants.REQUIRED_USER_GROUPS;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.ADDITIONAL_AZ_ATTR;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.AUD;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.AUTHORITIES;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.AUTH_TIME;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.AZP;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.CID;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.CLIENT_ID;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.EMAIL;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.EXP;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.GRANT_TYPE;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.IAT;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.ISS;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.JTI;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.NONCE;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.ORIGIN;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.REVOCABLE;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.REVOCATION_SIGNATURE;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.SCOPE;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.SUB;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.USER_ID;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.USER_NAME;
import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.ZONE_ID;
import static org.cloudfoundry.identity.uaa.oauth.token.RevocableToken.TokenFormat.JWT;
import static org.cloudfoundry.identity.uaa.oauth.token.RevocableToken.TokenFormat.OPAQUE;
import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_REFRESH_TOKEN;
import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_SAML2_BEARER;
import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_USER_TOKEN;
import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.REFRESH_TOKEN_SUFFIX;
import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.REQUEST_TOKEN_FORMAT;
import static org.cloudfoundry.identity.uaa.util.TokenValidation.validateAccessToken;
import static org.springframework.util.StringUtils.hasText;
/**
* This class provides token services for the UAA. It handles the production and
* consumption of UAA tokens.
*
*/
public class UaaTokenServices implements AuthorizationServerTokenServices, ResourceServerTokenServices,
InitializingBean, ApplicationEventPublisherAware {
public static final String UAA_REFRESH_TOKEN = "uaa.offline_token";
private final Log logger = LogFactory.getLog(getClass());
private UaaUserDatabase userDatabase = null;
private ClientServicesExtension clientDetailsService = null;
private String issuer = null;
private ApprovalStore approvalStore = null;
private ApplicationEventPublisher applicationEventPublisher;
private TokenPolicy tokenPolicy;
private RevocableTokenProvisioning tokenProvisioning;
private Set<String> excludedClaims = Collections.EMPTY_SET;
private boolean restrictRefreshGrant;
private UaaTokenEnhancer uaaTokenEnhancer = null;
private IdTokenCreator idTokenCreator;
private TokenValidityResolver accessTokenValidityResolver;
private TokenValidityResolver refreshTokenValidityResolver;
public Set<String> getExcludedClaims() {
return excludedClaims;
}
public void setExcludedClaims(Set<String> excludedClaims) {
this.excludedClaims = excludedClaims;
}
public RevocableTokenProvisioning getTokenProvisioning() {
return tokenProvisioning;
}
public void setTokenProvisioning(RevocableTokenProvisioning tokenProvisioning) {
this.tokenProvisioning = tokenProvisioning;
}
public void setUaaTokenEnhancer(UaaTokenEnhancer uaaTokenEnhancer) {
this.uaaTokenEnhancer = uaaTokenEnhancer;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@Override
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest request) throws AuthenticationException {
if (null == refreshTokenValue) {
throw new InvalidTokenException("Invalid refresh token (empty token)");
}
if (!"refresh_token".equals(request.getRequestParameters().get("grant_type"))) {
throw new InvalidGrantException("Invalid grant type: "
+ request.getRequestParameters().get("grant_type"));
}
TokenValidation tokenValidation = validateToken(refreshTokenValue);
Map<String, Object> claims = new HashMap<String,Object>(tokenValidation.getClaims()) {
@Override
public Object get(Object key) {
return super.remove(key);
}
};
refreshTokenValue = tokenValidation.getJwt().getEncoded();
@SuppressWarnings("unchecked")
ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE);
if (isRestrictRefreshGrant() && !tokenScopes.contains(UAA_REFRESH_TOKEN)) {
throw new InsufficientScopeException(String.format("Expected scope %s is missing", UAA_REFRESH_TOKEN));
}
String clientId = (String) claims.get(CID);
if (clientId == null || !clientId.equals(request.getClientId())) {
throw new InvalidGrantException("Wrong client for this refresh token: " + clientId);
}
//remove known claims
claims.remove(CLIENT_ID);
claims.remove(ORIGIN);
claims.remove(SUB);
claims.remove(ISS);
claims.remove(USER_NAME);
claims.remove(ZONE_ID);
claims.remove(IAT);
String userid = (String) claims.get(USER_ID);
String refreshTokenId = (String) claims.get(JTI);
String accessTokenId = generateUniqueTokenId();
boolean opaque = TokenConstants.OPAQUE.equals(request.getRequestParameters().get(TokenConstants.REQUEST_TOKEN_FORMAT));
Boolean revocableClaim = (Boolean)claims.get(REVOCABLE);
boolean revocable = opaque || (revocableClaim == null ? false : revocableClaim);
UaaUser user = userDatabase.retrieveUserById(userid);
ClientDetails client = clientDetailsService.loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
Integer refreshTokenExpiry = (Integer) claims.get(EXP);
long refreshTokenExpireDate = refreshTokenExpiry.longValue() * 1000l;
if (new Date(refreshTokenExpireDate).before(new Date())) {
throw new InvalidTokenException("Invalid refresh token expired at " + new Date(refreshTokenExpireDate));
}
// default request scopes to what is in the refresh token
Set<String> requestedScopes = request.getScope();
if (requestedScopes.isEmpty()) {
requestedScopes = new HashSet<>(tokenScopes);
}
// The user may not request scopes that were not part of the refresh
// token
if (tokenScopes.isEmpty() || !tokenScopes.containsAll(requestedScopes)) {
throw new InvalidScopeException("Unable to narrow the scope of the client authentication to "
+ requestedScopes + ".", new HashSet<>(tokenScopes));
}
// from this point on, we only care about the scopes requested, not what
// is in the refresh token
// ensure all requested scopes are approved: either automatically or
// explicitly by the user
String grantType = claims.get(GRANT_TYPE).toString();
checkForApproval(userid, clientId, requestedScopes,
getAutoApprovedScopes(grantType, tokenScopes, client)
);
String nonce = (String) claims.get(NONCE);
@SuppressWarnings("unchecked")
Map<String, String> additionalAuthorizationInfo = (Map<String, String>) claims.get(ADDITIONAL_AZ_ATTR);
String revocableHashSignature = (String)claims.get(REVOCATION_SIGNATURE);
if (hasText(revocableHashSignature)) {
String clientSecretForHash = client.getClientSecret();
if(clientSecretForHash != null && clientSecretForHash.split(" ").length > 1){
clientSecretForHash = clientSecretForHash.split(" ")[1];
}
String newRevocableHashSignature = UaaTokenUtils.getRevocableTokenSignature(client, clientSecretForHash, user);
if (!revocableHashSignature.equals(newRevocableHashSignature)) {
throw new TokenRevokedException("Invalid refresh token: revocable signature mismatch");
}
}
Set<String> audience = new HashSet<>((ArrayList<String>)claims.get(AUD));
Map<String, Object> additionalRootClaims = new HashMap<>();
claims.entrySet()
.stream()
.forEach(
entry -> additionalRootClaims.put(entry.getKey(), entry.getValue())
);
CompositeAccessToken accessToken =
createAccessToken(
accessTokenId,
user.getId(),
user,
(claims.get(AUTH_TIME) != null) ? new Date(((Long) claims.get(AUTH_TIME)) * 1000l) : null,
null,
requestedScopes,
clientId,
audience /*request.createOAuth2Request(client).getResourceIds()*/,
grantType,
refreshTokenValue,
nonce,
additionalAuthorizationInfo,
additionalRootClaims,
new HashSet<>(),
revocableHashSignature,
false,
null, //TODO populate response types
null,
revocable,
null,
null);
DefaultExpiringOAuth2RefreshToken expiringRefreshToken = new DefaultExpiringOAuth2RefreshToken(refreshTokenValue, new Date(refreshTokenExpireDate));
return persistRevocableToken(accessTokenId, refreshTokenId, accessToken, expiringRefreshToken, clientId, user.getId(), opaque, revocable);
}
private void checkForApproval(String userid,
String clientId,
Collection<String> requestedScopes,
Collection<String> autoApprovedScopes) {
if(autoApprovedScopes.containsAll(requestedScopes)) { return; }
Set<String> approvedScopes = new HashSet<>(autoApprovedScopes);
// Search through the users approvals for scopes that are requested, not
// auto approved, not expired,
// not DENIED and not approved more recently than when this access token
// was issued.
List<Approval> approvals = approvalStore.getApprovals(userid, clientId, IdentityZoneHolder.get().getId());
for (Approval approval : approvals) {
if (requestedScopes.contains(approval.getScope()) && approval.getStatus() == ApprovalStatus.APPROVED) {
if (!approval.isCurrentlyActive()) {
logger.debug("Approval " + approval + " has expired. Need to re-approve.");
throw new InvalidTokenException("Invalid token (approvals expired)");
}
approvedScopes.add(approval.getScope());
}
}
// Only issue the token if all the requested scopes have unexpired
// approvals made before the refresh token was
// issued OR if those scopes are auto approved
if (!approvedScopes.containsAll(requestedScopes)) {
logger.debug("All requested scopes " + requestedScopes + " were not approved " + approvedScopes);
Set<String> unapprovedScopes = new HashSet<String>(requestedScopes);
unapprovedScopes.removeAll(approvedScopes);
throw new InvalidTokenException("Invalid token (some requested scopes are not approved): "
+ unapprovedScopes);
}
}
private CompositeAccessToken createAccessToken(String tokenId,
String userId,
UaaUser user,
Date userAuthenticationTime,
Collection<GrantedAuthority> clientScopes,
Set<String> requestedScopes,
String clientId,
Set<String> resourceIds,
String grantType,
String refreshToken,
String nonce,
Map<String, String> additionalAuthorizationAttributes,
Map<String, Object> additionalRootClaims,
Set<String> responseTypes,
String revocableHashSignature,
boolean forceIdTokenCreation,
Set<String> externalGroupsForIdToken,
Map<String, List<String>> userAttributesForIdToken,
boolean revocable,
Set<String> authenticationMethods,
Set<String> authNContextClassRef) throws AuthenticationException {
CompositeAccessToken accessToken = new CompositeAccessToken(tokenId);
accessToken.setExpiration(accessTokenValidityResolver.resolve(clientId));
accessToken.setRefreshToken(refreshToken == null ? null : new DefaultOAuth2RefreshToken(refreshToken));
if (null == requestedScopes || requestedScopes.size() == 0) {
logger.debug("No scopes were granted");
throw new InvalidTokenException("No scopes were granted");
}
accessToken.setScope(requestedScopes);
ConcurrentMap<String, Object> info = new ConcurrentHashMap<>();
info.put(JTI, accessToken.getValue());
if (null != additionalAuthorizationAttributes) {
info.put(ADDITIONAL_AZ_ATTR, additionalAuthorizationAttributes);
}
if (nonce != null) {
info.put(NONCE, nonce);
}
accessToken.setAdditionalInformation(info);
String content;
Map<String, ?> jwtAccessToken = createJWTAccessToken(
accessToken,
userId,
user,
userAuthenticationTime,
clientScopes,
requestedScopes,
clientId,
resourceIds,
grantType,
revocableHashSignature,
revocable,
additionalRootClaims
);
try {
content = JsonUtils.writeValueAsString(jwtAccessToken);
} catch (JsonUtils.JsonUtilException e) {
throw new IllegalStateException("Cannot convert access token to JSON", e);
}
String token = JwtHelper.encode(content, getActiveKeyInfo().getSigner()).getEncoded();
// This setter copies the value and returns. Don't change.
accessToken.setValue(token);
if (shouldSendIdToken(clientScopes, requestedScopes, grantType, responseTypes, forceIdTokenCreation)) {
UserAuthenticationData authenticationData = new UserAuthenticationData(userAuthenticationTime,
authenticationMethods,
authNContextClassRef,
requestedScopes,
externalGroupsForIdToken,
userAttributesForIdToken,
nonce,
grantType,
tokenId);
String idTokenContent = null;
try {
idTokenContent = JsonUtils.writeValueAsString(idTokenCreator.create(clientId, userId, authenticationData));
} catch (RuntimeException | IdTokenCreationException e) {
throw new IllegalStateException("Cannot convert id token to JSON");
}
String encodedIdTokenContent = JwtHelper.encode(idTokenContent, KeyInfo.getActiveKey().getSigner()).getEncoded();
accessToken.setIdTokenValue(encodedIdTokenContent);
}
publish(new TokenIssuedEvent(accessToken, SecurityContextHolder.getContext().getAuthentication()));
return accessToken;
}
private boolean shouldSendIdToken(Collection<GrantedAuthority> clientScopes, Set<String> requestedScopes, String grantType, Set<String> responseTypes, boolean forceIdTokenCreation) {
boolean clientHasOpenIdScope = false;
if(null != clientScopes && !"client_credentials".equals(grantType)) {
for (GrantedAuthority scope : clientScopes) {
if (scope.getAuthority().equals("openid")) {
clientHasOpenIdScope = true;
break;
}
}
}
boolean idTokenExplicitlyRequested = requestedScopes.contains("openid") && responseTypes.contains(CompositeAccessToken.ID_TOKEN);
return forceIdTokenCreation || idTokenExplicitlyRequested || clientHasOpenIdScope;
}
private KeyInfo getActiveKeyInfo() {
return ofNullable(KeyInfo.getActiveKey())
.orElseThrow(() -> new InternalAuthenticationServiceException("Unable to sign token, misconfigured JWT signing keys"));
}
private Map<String, ?> createJWTAccessToken(OAuth2AccessToken token,
String userId,
UaaUser user,
Date userAuthenticationTime,
Collection<GrantedAuthority> clientScopes,
Set<String> requestedScopes,
String clientId,
Set<String> resourceIds,
String grantType,
String revocableHashSignature,
boolean revocable,
Map<String, Object> additionalRootClaims) {
Map<String, Object> claims = new LinkedHashMap<>();
claims.put(JTI, token.getAdditionalInformation().get(JTI));
claims.putAll(token.getAdditionalInformation());
if(additionalRootClaims != null) {
claims.putAll(additionalRootClaims);
}
claims.put(SUB, clientId);
if ("client_credentials".equals(grantType)) {
claims.put(AUTHORITIES, AuthorityUtils.authorityListToSet(clientScopes));
}
claims.put(OAuth2AccessToken.SCOPE, requestedScopes);
claims.put(CLIENT_ID, clientId);
claims.put(CID, clientId);
claims.put(AZP, clientId); //openId Connect
if (revocable) {
claims.put(REVOCABLE, true);
}
if (null != grantType) {
claims.put(GRANT_TYPE, grantType);
}
if (user!=null && userId!=null) {
claims.put(USER_ID, userId);
String origin = user.getOrigin();
if (StringUtils.hasLength(origin)) {
claims.put(ORIGIN, origin);
}
String username = user.getUsername();
claims.put(USER_NAME, username == null ? userId : username);
String userEmail = user.getEmail();
if (userEmail != null) {
claims.put(EMAIL, userEmail);
}
if (userAuthenticationTime!=null) {
claims.put(AUTH_TIME, userAuthenticationTime.getTime() / 1000);
}
claims.put(SUB, userId);
}
if (StringUtils.hasText(revocableHashSignature)) {
claims.put(REVOCATION_SIGNATURE, revocableHashSignature);
}
claims.put(IAT, System.currentTimeMillis() / 1000);
claims.put(EXP, token.getExpiration().getTime() / 1000);
if (getTokenEndpoint() != null) {
claims.put(ISS, getTokenEndpoint());
claims.put(ZONE_ID,IdentityZoneHolder.get().getId());
}
// TODO: different values for audience in the AT and RT. Need to sync
// them up
claims.put(AUD, resourceIds);
for (String excludedClaim : getExcludedClaims()) {
claims.remove(excludedClaim);
}
return claims;
}
@Override
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
String userId = null;
Date userAuthenticationTime = null;
UaaUser user = null;
boolean wasIdTokenRequestedThroughAuthCodeScopeParameter = false;
Set<String> authenticationMethods = null;
Set<String> authNContextClassRef = null;
ClientDetails client = clientDetailsService.loadClientByClientId(authentication.getOAuth2Request().getClientId(), IdentityZoneHolder.get().getId());
Collection<GrantedAuthority> clientScopes = null;
// Clients should really by different kinds of users
if (authentication.isClientOnly()) {
clientScopes = client.getAuthorities();
} else {
clientScopes = new ArrayList<GrantedAuthority>();
for(String scope : client.getScope()) {
clientScopes.add(new XOAuthUserAuthority(scope));
}
userId = getUserId(authentication);
user = userDatabase.retrieveUserById(userId);
if (authentication.getUserAuthentication() instanceof UaaAuthentication) {
userAuthenticationTime = new Date(((UaaAuthentication)authentication.getUserAuthentication()).getAuthenticatedTime());
authenticationMethods = ((UaaAuthentication) authentication.getUserAuthentication()).getAuthenticationMethods();
authNContextClassRef = ((UaaAuthentication) authentication.getUserAuthentication()).getAuthContextClassRef();
}
validateRequiredUserGroups(user, client);
}
String clientSecretForHash = client.getClientSecret();
if(clientSecretForHash != null && clientSecretForHash.split(" ").length > 1){
clientSecretForHash = clientSecretForHash.split(" ")[1];
}
String revocableHashSignature = UaaTokenUtils.getRevocableTokenSignature(client, clientSecretForHash, user);
String tokenId = generateUniqueTokenId();
String refreshTokenId = generateUniqueTokenId() + REFRESH_TOKEN_SUFFIX;
boolean opaque = opaqueTokenRequired(authentication);
boolean accessTokenRevocable = opaque || IdentityZoneHolder.get().getConfig().getTokenPolicy().isJwtRevocable();
boolean refreshTokenRevocable = accessTokenRevocable || TokenConstants.TokenFormat.OPAQUE.getStringValue().equals(IdentityZoneHolder.get().getConfig().getTokenPolicy().getRefreshTokenFormat());
OAuth2RefreshToken refreshToken = null;
Map<String,Object> additionalRootClaims = null;
if (uaaTokenEnhancer != null) {
additionalRootClaims = new HashMap<>();
additionalRootClaims.putAll(uaaTokenEnhancer.enhance(emptyMap(), authentication));
}
if(client.getAuthorizedGrantTypes().contains(GRANT_TYPE_REFRESH_TOKEN)){
refreshToken = createRefreshToken(user, refreshTokenId, authentication, revocableHashSignature, refreshTokenRevocable, additionalRootClaims);
}
String clientId = authentication.getOAuth2Request().getClientId();
Set<String> userScopes = authentication.getOAuth2Request().getScope();
Map<String, String> requestParameters = authentication.getOAuth2Request().getRequestParameters();
String grantType = requestParameters.get("grant_type");
Set<String> modifiableUserScopes = new LinkedHashSet<>(userScopes);
Set<String> externalGroupsForIdToken = Collections.EMPTY_SET;
Map<String,List<String>> userAttributesForIdToken = Collections.EMPTY_MAP;
if (authentication.getUserAuthentication() instanceof UaaAuthentication) {
externalGroupsForIdToken = ((UaaAuthentication)authentication.getUserAuthentication()).getExternalGroups();
userAttributesForIdToken = ((UaaAuthentication)authentication.getUserAuthentication()).getUserAttributes();
}
String nonce = requestParameters.get(NONCE);
Map<String, String> additionalAuthorizationAttributes =
getAdditionalAuthorizationAttributes(
requestParameters.get("authorities")
);
if ("authorization_code".equals(requestParameters.get(OAuth2Utils.GRANT_TYPE)) &&
"code".equals(requestParameters.get(OAuth2Utils.RESPONSE_TYPE)) &&
requestParameters.get(OAuth2Utils.SCOPE)!=null &&
Arrays.asList(requestParameters.get(OAuth2Utils.SCOPE).split(" ")).contains("openid")) {
wasIdTokenRequestedThroughAuthCodeScopeParameter = true;
}
Set<String> responseTypes = extractResponseTypes(authentication);
CompositeAccessToken accessToken =
createAccessToken(
tokenId,
userId,
user,
userAuthenticationTime,
clientScopes,
modifiableUserScopes,
clientId,
authentication.getOAuth2Request().getResourceIds(),
grantType,
refreshToken != null ? refreshToken.getValue() : null,
nonce,
additionalAuthorizationAttributes,
additionalRootClaims,
responseTypes,
revocableHashSignature,
wasIdTokenRequestedThroughAuthCodeScopeParameter,
externalGroupsForIdToken,
userAttributesForIdToken,
accessTokenRevocable,
authenticationMethods,
authNContextClassRef);
return persistRevocableToken(tokenId, refreshTokenId, accessToken, refreshToken, clientId, userId, opaque, accessTokenRevocable);
}
public static void validateRequiredUserGroups(UaaUser user, ClientDetails client) {
Collection<String> requiredUserGroups = ofNullable((Collection<String>) client.getAdditionalInformation().get(REQUIRED_USER_GROUPS)).orElse(emptySet());
if (!UaaTokenUtils.hasRequiredUserAuthorities(requiredUserGroups, user.getAuthorities())) {
throw new InvalidTokenException("User does not meet the client's required group criteria.");
}
}
public CompositeAccessToken persistRevocableToken(String tokenId,
String refreshTokenId,
CompositeAccessToken token,
OAuth2RefreshToken refreshToken,
String clientId,
String userId,
boolean opaque,
boolean revocable) {
String scope = token.getScope().toString();
long now = System.currentTimeMillis();
if (revocable) {
RevocableToken revocableAccessToken = new RevocableToken()
.setTokenId(tokenId)
.setClientId(clientId)
.setExpiresAt(token.getExpiration().getTime())
.setIssuedAt(now)
.setFormat(opaque ? OPAQUE.name() : JWT.name())
.setResponseType(RevocableToken.TokenType.ACCESS_TOKEN)
.setZoneId(IdentityZoneHolder.get().getId())
.setUserId(userId)
.setScope(scope)
.setValue(token.getValue());
try {
tokenProvisioning.create(revocableAccessToken, IdentityZoneHolder.get().getId());
} catch (DuplicateKeyException updateInstead) {
//TODO this is an uninteded side effect of reusing access token IDs
tokenProvisioning.update(tokenId, revocableAccessToken, IdentityZoneHolder.get().getId());
}
}
boolean refreshTokenOpaque = opaque || TokenConstants.TokenFormat.OPAQUE.getStringValue().equals(IdentityZoneHolder.get().getConfig().getTokenPolicy().getRefreshTokenFormat());
boolean refreshTokenRevocable = refreshTokenOpaque || IdentityZoneHolder.get().getConfig().getTokenPolicy().isJwtRevocable();
boolean refreshTokenUnique = IdentityZoneHolder.get().getConfig().getTokenPolicy().isRefreshTokenUnique();
if (refreshToken!=null && refreshTokenRevocable) {
RevocableToken revocableRefreshToken = new RevocableToken()
.setTokenId(refreshTokenId)
.setClientId(clientId)
.setExpiresAt(((ExpiringOAuth2RefreshToken) refreshToken).getExpiration().getTime())
.setIssuedAt(now)
.setFormat(refreshTokenOpaque ? OPAQUE.name() : JWT.name())
.setResponseType(RevocableToken.TokenType.REFRESH_TOKEN)
.setZoneId(IdentityZoneHolder.get().getId())
.setUserId(userId)
.setScope(scope)
.setValue(refreshToken.getValue());
try {
if(refreshTokenUnique) {
tokenProvisioning.deleteRefreshTokensForClientAndUserId(clientId, userId, IdentityZoneHolder.get().getId());
}
tokenProvisioning.create(revocableRefreshToken, IdentityZoneHolder.get().getId());
} catch (DuplicateKeyException ignore) {
//no need to store refresh tokens again
}
}
CompositeAccessToken result = new CompositeAccessToken(opaque ? tokenId : token.getValue());
result.setIdTokenValue(token.getIdTokenValue());
result.setExpiration(token.getExpiration());
result.setAdditionalInformation(token.getAdditionalInformation());
result.setScope(token.getScope());
result.setTokenType(token.getTokenType());
result.setRefreshToken(refreshToken==null ? null : new DefaultOAuth2RefreshToken(refreshTokenOpaque ? refreshTokenId : refreshToken.getValue()));
return result;
}
protected boolean opaqueTokenRequired(OAuth2Authentication authentication) {
Map<String, String> parameters = authentication.getOAuth2Request().getRequestParameters();
return TokenConstants.OPAQUE.equals(parameters.get(REQUEST_TOKEN_FORMAT)) ||
GRANT_TYPE_USER_TOKEN.equals(parameters.get(GRANT_TYPE));
}
/**
* If an only if the stored request has response_type=code AND
* the request parameters override it using another response_type parameter
* this method will return the requested response_type rather than the stored
* @param authentication
* @return
*/
protected Set<String> extractResponseTypes(OAuth2Authentication authentication) {
Set<String> responseTypes = authentication.getOAuth2Request().getResponseTypes();
if (responseTypes!=null && responseTypes.size()==1) {
String storedResponseType = responseTypes.iterator().next();
String requesedResponseType = authentication.getOAuth2Request().getRequestParameters().get(OAuth2Utils.RESPONSE_TYPE);
if ("code".equals(storedResponseType) &&
requesedResponseType!=null) {
responseTypes = OAuth2Utils.parseParameterList(requesedResponseType);
}
}
return responseTypes;
}
/**
* This method searches the authorities in the request for
* additionalAuthorizationAttributes
* and returns a map of these attributes that will later be added to the
* token
*
* @param authoritiesJson
* @return
*/
private Map<String, String> getAdditionalAuthorizationAttributes(String authoritiesJson) {
if (StringUtils.hasLength(authoritiesJson)) {
try {
Map<String, Object> authorities = JsonUtils.readValue(authoritiesJson, new TypeReference<Map<String, Object>>() {});
Object az_attr = authorities.get("az_attr");
if(az_attr == null)
return null;
// validate az_attr content with Map<String, String>>
Map<String, String> additionalAuthorizationAttributes =
JsonUtils.readValue(JsonUtils.writeValueAsBytes(az_attr), new TypeReference<Map<String, String>>() {});
return additionalAuthorizationAttributes;
} catch (Throwable t) {
logger.error("Unable to read additionalAuthorizationAttributes", t);
}
}
return null;
}
private ExpiringOAuth2RefreshToken createRefreshToken(UaaUser user, String tokenId,
OAuth2Authentication authentication,
String revocableHashSignature,
boolean revocable,
Map<String,Object> externalAttributes) {
String grantType = authentication.getOAuth2Request().getRequestParameters().get("grant_type");
Set<String> scope = authentication.getOAuth2Request().getScope();
if (!isRefreshTokenSupported(grantType, scope)) {
return null;
}
Map<String, String> additionalAuthorizationAttributes = getAdditionalAuthorizationAttributes(authentication
.getOAuth2Request().getRequestParameters().get("authorities"));
Date validitySeconds = refreshTokenValidityResolver.resolve(authentication.getOAuth2Request().getClientId());
ExpiringOAuth2RefreshToken token = new DefaultExpiringOAuth2RefreshToken(tokenId, validitySeconds);
String content;
try {
content = JsonUtils.writeValueAsString(
createJWTRefreshToken(
token,
tokenId,
user,
authentication.getOAuth2Request().getScope(),
authentication.getOAuth2Request().getClientId(),
grantType,
additionalAuthorizationAttributes,authentication.getOAuth2Request().getResourceIds(),
revocableHashSignature,
revocable,
externalAttributes
)
);
} catch (JsonUtils.JsonUtilException e) {
throw new IllegalStateException("Cannot convert access token to JSON", e);
}
String jwtToken = JwtHelper.encode(content, getActiveKeyInfo().getSigner()).getEncoded();
ExpiringOAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken(jwtToken, token.getExpiration());
return refreshToken;
}
protected String getUserId(OAuth2Authentication authentication) {
return Origin.getUserId(authentication.getUserAuthentication());
}
private Map<String, ?> createJWTRefreshToken(
OAuth2RefreshToken token,
String tokenId,
UaaUser user,
Set<String> scopes,
String clientId,
String grantType,
Map<String, String> additionalAuthorizationAttributes,
Set<String> resourceIds,
String revocableSignature,
boolean revocable,
Map<String, Object> externalAttributes) {
Map<String, Object> response = new LinkedHashMap<>();
response.put(JTI, tokenId);
response.put(SUB, user.getId());
response.put(SCOPE, scopes);
if (null != additionalAuthorizationAttributes) {
response.put(ADDITIONAL_AZ_ATTR, additionalAuthorizationAttributes);
}
if (null != externalAttributes) {
response.putAll(externalAttributes);
}
response.put(IAT, System.currentTimeMillis() / 1000);
if (((ExpiringOAuth2RefreshToken) token).getExpiration() != null) {
response.put(EXP, ((ExpiringOAuth2RefreshToken) token).getExpiration().getTime() / 1000);
}
response.put(CID, clientId);
response.put(CLIENT_ID, clientId);
if (getTokenEndpoint() != null) {
response.put(ISS, getTokenEndpoint());
response.put(ZONE_ID,IdentityZoneHolder.get().getId());
}
if (revocable) {
response.put(ClaimConstants.REVOCABLE, true);
}
if (null != grantType) {
response.put(GRANT_TYPE, grantType);
}
if (user!=null) {
response.put(USER_NAME, user.getUsername());
response.put(ORIGIN, user.getOrigin());
response.put(USER_ID, user.getId());
}
if (hasText(revocableSignature)) {
response.put(REVOCATION_SIGNATURE, revocableSignature);
}
response.put(AUD, resourceIds);
return response;
}
protected String generateUniqueTokenId() {
return UUID.randomUUID().toString().replace("-", "");
}
/**
* Check the current authorization request to indicate whether a refresh
* token should be issued or not.
*
* @param grantType the current grant type
* @param scope
* @return boolean to indicate if refresh token is supported
*/
protected boolean isRefreshTokenSupported(String grantType, Set<String> scope) {
if (!isRestrictRefreshGrant()) {
return "authorization_code".equals(grantType) ||
"password".equals(grantType) ||
GRANT_TYPE_USER_TOKEN.equals(grantType) ||
GRANT_TYPE_REFRESH_TOKEN.equals(grantType) ||
GRANT_TYPE_SAML2_BEARER.equals(grantType);
} else {
return scope.contains(UAA_REFRESH_TOKEN);
}
}
@Override
public void afterPropertiesSet() throws URISyntaxException {
Assert.notNull(clientDetailsService, "clientDetailsService must be set");
Assert.notNull(issuer, "issuer must be set");
Assert.notNull(approvalStore, "approvalStore must be set");
new URI(issuer); //assert the issuer is a valid url at startup.
}
public void setUserDatabase(UaaUserDatabase userDatabase) {
this.userDatabase = userDatabase;
}
@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
if (StringUtils.isEmpty(accessToken)) {
throw new InvalidTokenException("Invalid access token value, must be at least 30 characters");
}
TokenValidation tokenValidation = validateToken(accessToken)
.checkAccessToken()
.throwIfInvalid();
Map<String, Object> claims = tokenValidation.getClaims();
accessToken = tokenValidation.getJwt().getEncoded();
// Check token expiry
Long expiration = Long.valueOf(claims.get(EXP).toString());
if (expiration != null && new Date(expiration * 1000l).before(new Date())) {
throw new InvalidTokenException("Invalid access token: expired at " + new Date(expiration * 1000l));
}
@SuppressWarnings("unchecked")
ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE);
AuthorizationRequest authorizationRequest = new AuthorizationRequest((String) claims.get(CLIENT_ID),
scopes);
ArrayList<String> rids = (ArrayList<String>) claims.get(AUD);
//TODO - Fix null resource IDs for a client_credentials request to /oauth/token
Set<String> resourceIds = Collections.unmodifiableSet(rids==null?new HashSet<>():new HashSet<>(rids));
authorizationRequest.setResourceIds(resourceIds);
authorizationRequest.setApproved(true);
Collection<String> defaultUserAuthorities = IdentityZoneHolder.get().getConfig().getUserConfig().getDefaultGroups();
Collection<? extends GrantedAuthority> authorities =
AuthorityUtils.commaSeparatedStringToAuthorityList(
StringUtils.collectionToCommaDelimitedString(defaultUserAuthorities)
);
if (claims.containsKey("authorities")) {
Object authoritiesFromClaims = claims.get("authorities");
if (authoritiesFromClaims instanceof String) {
authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) authoritiesFromClaims);
}
if (authoritiesFromClaims instanceof Collection) {
authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
.collectionToCommaDelimitedString((Collection<?>) authoritiesFromClaims));
}
}
Authentication userAuthentication = null;
// Is this a user token - minimum info is user_id
if (claims.containsKey(USER_ID)) {
UaaUser user = userDatabase.retrieveUserById((String)claims.get(USER_ID));
UaaPrincipal principal = new UaaPrincipal(user);
userAuthentication = new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES, null);
} else {
authorizationRequest.setAuthorities(authorities);
}