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
|
package com.ss.project.xia17user.config.security.auth2;
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.Principal; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.*;
import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ss.project.xia17user.common.utils.ResponseUtil; import com.ss.project.xia17user.config.security.SecurityUtils; import com.ss.project.xia17user.service.ClientService; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.keygen.Base64StringKeyGenerator; import org.springframework.security.crypto.keygen.StringKeyGenerator; import org.springframework.security.oauth2.core.*; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.core.endpoint.PkceParameterNames; import org.springframework.security.oauth2.core.oidc.OidcScopes; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode; import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.util.matcher.AndRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.NegatedRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.*; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.UriComponentsBuilder;
public class CustomAuth2AuthorizationEndpointFilter extends OncePerRequestFilter {
public static final String DEFAULT_AUTHORIZATION_ENDPOINT_URI = "/oauth2/authorize";
private static final OAuth2TokenType STATE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.STATE); private static final String PKCE_ERROR_URI = "https://tools.ietf.org/html/rfc7636#section-4.4.1";
private final RegisteredClientRepository registeredClientRepository; private final OAuth2AuthorizationService authorizationService; private final RequestMatcher authorizationRequestMatcher; private final RequestMatcher userConsentMatcher; private final StringKeyGenerator codeGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96); private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder()); private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private final ClientService clientService; private final UserConsentPage userConsentPage;
public CustomAuth2AuthorizationEndpointFilter(RegisteredClientRepository registeredClientRepository, OAuth2AuthorizationService authorizationService, ClientService clientService , UserConsentPage userConsentPage) { this(registeredClientRepository, authorizationService, DEFAULT_AUTHORIZATION_ENDPOINT_URI ,clientService ,userConsentPage); }
public CustomAuth2AuthorizationEndpointFilter(RegisteredClientRepository registeredClientRepository, OAuth2AuthorizationService authorizationService, String authorizationEndpointUri , ClientService clientService , UserConsentPage userConsentPage) { Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null"); Assert.notNull(authorizationService, "authorizationService cannot be null"); Assert.hasText(authorizationEndpointUri, "authorizationEndpointUri cannot be empty"); this.registeredClientRepository = registeredClientRepository; this.authorizationService = authorizationService; this.clientService = clientService; this.userConsentPage = userConsentPage; RequestMatcher authorizationRequestGetMatcher = new AntPathRequestMatcher( authorizationEndpointUri, HttpMethod.GET.name()); RequestMatcher authorizationRequestPostMatcher = new AntPathRequestMatcher( authorizationEndpointUri, HttpMethod.POST.name()); RequestMatcher openidScopeMatcher = request -> { String scope = request.getParameter(OAuth2ParameterNames.SCOPE); return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID); }; RequestMatcher consentActionMatcher = request -> request.getParameter(UserConsentPage.CONSENT_ACTION_PARAMETER_NAME) != null; this.authorizationRequestMatcher = new OrRequestMatcher( authorizationRequestGetMatcher, new AndRequestMatcher( authorizationRequestPostMatcher, openidScopeMatcher, new NegatedRequestMatcher(consentActionMatcher))); this.userConsentMatcher = new AndRequestMatcher( authorizationRequestPostMatcher, consentActionMatcher); }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (this.authorizationRequestMatcher.matches(request)) { processAuthorizationRequest(request, response, filterChain); } else if (this.userConsentMatcher.matches(request)) { processUserConsent(request, response); } else { filterChain.doFilter(request, response); } }
private void processAuthorizationRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
OAuth2AuthorizationRequestContext authorizationRequestContext = new OAuth2AuthorizationRequestContext( request.getRequestURL().toString(), OAuth2EndpointUtils.getParameters(request));
validateAuthorizationRequest(authorizationRequestContext);
if (authorizationRequestContext.hasError()) { if (authorizationRequestContext.isRedirectOnError()) { sendErrorResponse(request, response, authorizationRequestContext.resolveRedirectUri(), authorizationRequestContext.getError(), authorizationRequestContext.getState()); } else { sendErrorResponse(request,response, authorizationRequestContext.getError()); } return; }
Authentication principal = SecurityContextHolder.getContext().getAuthentication(); if (!isPrincipalAuthenticated(principal)) { filterChain.doFilter(request, response); return; }
RegisteredClient registeredClient = authorizationRequestContext.getRegisteredClient();
if (!clientService.checkUserClientPermission(SecurityUtils.userId(),registeredClient.getClientId())){ logger.error("当前登录的用户[" + SecurityUtils.userId() + "]不能访问ClientId[" + registeredClient.getClientId() + "]"); sendError(request,response,new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED,"你没有权限访问该项目","")); return; }
OAuth2AuthorizationRequest authorizationRequest = authorizationRequestContext.buildAuthorizationRequest(); OAuth2Authorization.Builder builder = OAuth2Authorization.withRegisteredClient(registeredClient) .principalName(principal.getName()) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .attribute(Principal.class.getName(), principal) .attribute(OAuth2AuthorizationRequest.class.getName(), authorizationRequest);
if (requireUserConsent(registeredClient, authorizationRequest)) { String state = this.stateGenerator.generateKey(); OAuth2Authorization authorization = builder .attribute(OAuth2ParameterNames.STATE, state) .build(); this.authorizationService.save(authorization);
this.userConsentPage.display(request, response, registeredClient, authorization); } else { Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plus(5, ChronoUnit.MINUTES); OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode( this.codeGenerator.generateKey(), issuedAt, expiresAt); OAuth2Authorization authorization = builder .token(authorizationCode) .attribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizationRequest.getScopes()) .build(); this.authorizationService.save(authorization);
sendAuthorizationResponse(request, response, authorizationRequestContext.resolveRedirectUri(), authorizationCode, authorizationRequest.getState()); } }
private static boolean requireUserConsent(RegisteredClient registeredClient, OAuth2AuthorizationRequest authorizationRequest) { if (authorizationRequest.getScopes().contains(OidcScopes.OPENID) && authorizationRequest.getScopes().size() == 1) { return false; } return registeredClient.getClientSettings().requireUserConsent(); }
private void processUserConsent(HttpServletRequest request, HttpServletResponse response) throws IOException {
UserConsentRequestContext userConsentRequestContext = new UserConsentRequestContext( request.getRequestURL().toString(), OAuth2EndpointUtils.getParameters(request));
validateUserConsentRequest(userConsentRequestContext);
if (userConsentRequestContext.hasError()) { if (userConsentRequestContext.isRedirectOnError()) { sendErrorResponse(request, response, userConsentRequestContext.resolveRedirectUri(), userConsentRequestContext.getError(), userConsentRequestContext.getState()); } else { sendErrorResponse(request,response, userConsentRequestContext.getError()); } return; }
if (!this.userConsentPage.isConsentApproved(request)) { this.authorizationService.remove(userConsentRequestContext.getAuthorization()); OAuth2Error error = createError(OAuth2ErrorCodes.ACCESS_DENIED, "用户已取消授权"); sendErrorResponse(request, response, userConsentRequestContext.resolveRedirectUri(), error, userConsentRequestContext.getAuthorizationRequest().getState()); return; }
Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plus(5, ChronoUnit.MINUTES); OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode( this.codeGenerator.generateKey(), issuedAt, expiresAt); Set<String> authorizedScopes = userConsentRequestContext.getScopes(); if (userConsentRequestContext.getAuthorizationRequest().getScopes().contains(OidcScopes.OPENID)) { authorizedScopes.add(OidcScopes.OPENID); } OAuth2Authorization authorization = OAuth2Authorization.from(userConsentRequestContext.getAuthorization()) .token(authorizationCode) .attributes(attrs -> { attrs.remove(OAuth2ParameterNames.STATE); attrs.put(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizedScopes); }) .build(); this.authorizationService.save(authorization);
sendAuthorizationResponse(request, response, userConsentRequestContext.resolveRedirectUri(), authorizationCode, userConsentRequestContext.getAuthorizationRequest().getState()); }
private void validateAuthorizationRequest(OAuth2AuthorizationRequestContext authorizationRequestContext) {
if (!StringUtils.hasText(authorizationRequestContext.getClientId()) || authorizationRequestContext.getParameters().get(OAuth2ParameterNames.CLIENT_ID).size() != 1) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, "client_id 参数异常")); return; } RegisteredClient registeredClient = this.registeredClientRepository.findByClientId( authorizationRequestContext.getClientId()); if (registeredClient == null) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, "没有找到已注册的客户端:" + authorizationRequestContext.getClientId())); return; } else if (!registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.AUTHORIZATION_CODE)) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, "暂时支持AUTHORIZATION_CODE方式授权")); return; } authorizationRequestContext.setRegisteredClient(registeredClient);
if (StringUtils.hasText(authorizationRequestContext.getRedirectUri())) { if (!registeredClient.getRedirectUris().contains(authorizationRequestContext.getRedirectUri()) || authorizationRequestContext.getParameters().get(OAuth2ParameterNames.REDIRECT_URI).size() != 1) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, "授权回调地址异常")); return; } } else if (authorizationRequestContext.isAuthenticationRequest() || registeredClient.getRedirectUris().size() != 1) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI)); return; } authorizationRequestContext.setRedirectOnError(true);
if (!StringUtils.hasText(authorizationRequestContext.getResponseType()) || authorizationRequestContext.getParameters().get(OAuth2ParameterNames.RESPONSE_TYPE).size() != 1) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.RESPONSE_TYPE +"参数异常")); return; } else if (!authorizationRequestContext.getResponseType().equals(OAuth2AuthorizationResponseType.CODE.getValue())) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, OAuth2ParameterNames.RESPONSE_TYPE+"参数异常")); return; }
Set<String> requestedScopes = authorizationRequestContext.getScopes(); Set<String> allowedScopes = registeredClient.getScopes(); if (!requestedScopes.isEmpty() && !allowedScopes.containsAll(requestedScopes)) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_SCOPE, "授权范围异常")); return; }
String codeChallenge = authorizationRequestContext.getParameters().getFirst(PkceParameterNames.CODE_CHALLENGE); if (StringUtils.hasText(codeChallenge)) { if (authorizationRequestContext.getParameters().get(PkceParameterNames.CODE_CHALLENGE).size() != 1) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE, PKCE_ERROR_URI)); return; }
String codeChallengeMethod = authorizationRequestContext.getParameters().getFirst(PkceParameterNames.CODE_CHALLENGE_METHOD); if (StringUtils.hasText(codeChallengeMethod)) { if (authorizationRequestContext.getParameters().get(PkceParameterNames.CODE_CHALLENGE_METHOD).size() != 1 || (!"S256".equals(codeChallengeMethod) && !"plain".equals(codeChallengeMethod))) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD, PKCE_ERROR_URI)); } } } else if (registeredClient.getClientSettings().requireProofKey()) { authorizationRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE, PKCE_ERROR_URI)); } }
private void validateUserConsentRequest(UserConsentRequestContext userConsentRequestContext) {
if (!StringUtils.hasText(userConsentRequestContext.getState()) || userConsentRequestContext.getParameters().get(OAuth2ParameterNames.STATE).size() != 1) { userConsentRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE+"参数异常")); return; } OAuth2Authorization authorization = this.authorizationService.findByToken( userConsentRequestContext.getState(), STATE_TOKEN_TYPE); if (authorization == null) { userConsentRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, "没有找到state")); return; } userConsentRequestContext.setAuthorization(authorization);
Authentication principal = SecurityContextHolder.getContext().getAuthentication(); if (!isPrincipalAuthenticated(principal) || !principal.getName().equals(authorization.getPrincipalName())) { userConsentRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, "登录已经失效")); return; }
if (!StringUtils.hasText(userConsentRequestContext.getClientId()) || userConsentRequestContext.getParameters().get(OAuth2ParameterNames.CLIENT_ID).size() != 1) { userConsentRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, "client_id参数异常" )); return; } RegisteredClient registeredClient = this.registeredClientRepository.findByClientId( userConsentRequestContext.getClientId()); if (registeredClient == null || !registeredClient.getId().equals(authorization.getRegisteredClientId())) { userConsentRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_REQUEST, "没有找到已注册的客户端:" + userConsentRequestContext.getClientId())); return; } userConsentRequestContext.setRegisteredClient(registeredClient); userConsentRequestContext.setRedirectOnError(true);
Set<String> requestedScopes = userConsentRequestContext.getAuthorizationRequest().getScopes(); Set<String> authorizedScopes = userConsentRequestContext.getScopes(); if (!authorizedScopes.isEmpty() && !requestedScopes.containsAll(authorizedScopes)) { userConsentRequestContext.setError( createError(OAuth2ErrorCodes.INVALID_SCOPE,"授权范围异常")); return; } }
private void sendAuthorizationResponse(HttpServletRequest request, HttpServletResponse response, String redirectUri, OAuth2AuthorizationCode authorizationCode, String state) throws IOException {
UriComponentsBuilder uriBuilder = UriComponentsBuilder .fromUriString(redirectUri) .queryParam(OAuth2ParameterNames.CODE, authorizationCode.getTokenValue()); if (StringUtils.hasText(state)) { uriBuilder.queryParam(OAuth2ParameterNames.STATE, state); } this.redirectStrategy.sendRedirect(request, response, uriBuilder.toUriString()); }
private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, String redirectUri, OAuth2Error error, String state) throws IOException {
UriComponentsBuilder uriBuilder = UriComponentsBuilder .fromUriString(redirectUri) .queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode()); if (StringUtils.hasText(error.getDescription())) { uriBuilder.queryParam(OAuth2ParameterNames.ERROR_DESCRIPTION, error.getDescription()); } if (StringUtils.hasText(error.getUri())) { uriBuilder.queryParam(OAuth2ParameterNames.ERROR_URI, error.getUri()); } if (StringUtils.hasText(state)) { uriBuilder.queryParam(OAuth2ParameterNames.STATE, state); } this.redirectStrategy.sendRedirect(request, response, uriBuilder.toUriString()); }
private void sendErrorResponse(HttpServletRequest request ,HttpServletResponse response, OAuth2Error error) throws IOException {
this.sendError(request,response,error); }
private void sendError(HttpServletRequest request, HttpServletResponse response, OAuth2Error error){ ResponseUtil.sendError(request,response,new OAuth2AuthenticationException(error)); }
private static OAuth2Error createError(String errorCode, String desc) { return createError(errorCode, desc, "https://tools.ietf.org/html/rfc6749#section-4.1.2.1"); }
private static OAuth2Error createError(String errorCode, String desc, String errorUri) { return new OAuth2Error(errorCode, desc, errorUri); }
private static boolean isPrincipalAuthenticated(Authentication principal) { return principal != null && !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass()) && principal.isAuthenticated(); }
private static class OAuth2AuthorizationRequestContext extends AbstractRequestContext { private final String responseType; private final String redirectUri;
private OAuth2AuthorizationRequestContext( String authorizationUri, MultiValueMap<String, String> parameters) { super(authorizationUri, parameters, parameters.getFirst(OAuth2ParameterNames.CLIENT_ID), parameters.getFirst(OAuth2ParameterNames.STATE), extractScopes(parameters)); this.responseType = parameters.getFirst(OAuth2ParameterNames.RESPONSE_TYPE); this.redirectUri = parameters.getFirst(OAuth2ParameterNames.REDIRECT_URI); }
private static Set<String> extractScopes(MultiValueMap<String, String> parameters) { String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE); return StringUtils.hasText(scope) ? new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " "))) : Collections.emptySet(); }
private String getResponseType() { return this.responseType; }
private String getRedirectUri() { return this.redirectUri; }
private boolean isAuthenticationRequest() { return getScopes().contains(OidcScopes.OPENID); }
@Override protected String resolveRedirectUri() { return StringUtils.hasText(getRedirectUri()) ? getRedirectUri() : getRegisteredClient().getRedirectUris().iterator().next(); }
private OAuth2AuthorizationRequest buildAuthorizationRequest() { return OAuth2AuthorizationRequest.authorizationCode() .authorizationUri(getAuthorizationUri()) .clientId(getClientId()) .redirectUri(getRedirectUri()) .scopes(getScopes()) .state(getState()) .additionalParameters(additionalParameters -> getParameters().entrySet().stream() .filter(e -> !e.getKey().equals(OAuth2ParameterNames.RESPONSE_TYPE) && !e.getKey().equals(OAuth2ParameterNames.CLIENT_ID) && !e.getKey().equals(OAuth2ParameterNames.REDIRECT_URI) && !e.getKey().equals(OAuth2ParameterNames.SCOPE) && !e.getKey().equals(OAuth2ParameterNames.STATE)) .forEach(e -> additionalParameters.put(e.getKey(), e.getValue().get(0)))) .build(); } }
private static class UserConsentRequestContext extends AbstractRequestContext { private OAuth2Authorization authorization;
private UserConsentRequestContext( String authorizationUri, MultiValueMap<String, String> parameters) { super(authorizationUri, parameters, parameters.getFirst(OAuth2ParameterNames.CLIENT_ID), parameters.getFirst(OAuth2ParameterNames.STATE), extractScopes(parameters)); }
private static Set<String> extractScopes(MultiValueMap<String, String> parameters) { List<String> scope = parameters.get(OAuth2ParameterNames.SCOPE); return !CollectionUtils.isEmpty(scope) ? new HashSet<>(scope) : Collections.emptySet(); }
private OAuth2Authorization getAuthorization() { return this.authorization; }
private void setAuthorization(OAuth2Authorization authorization) { this.authorization = authorization; }
@Override protected String resolveRedirectUri() { OAuth2AuthorizationRequest authorizationRequest = getAuthorizationRequest(); return StringUtils.hasText(authorizationRequest.getRedirectUri()) ? authorizationRequest.getRedirectUri() : getRegisteredClient().getRedirectUris().iterator().next(); }
private OAuth2AuthorizationRequest getAuthorizationRequest() { return getAuthorization().getAttribute(OAuth2AuthorizationRequest.class.getName()); } }
private abstract static class AbstractRequestContext { private final String authorizationUri; private final MultiValueMap<String, String> parameters; private final String clientId; private final String state; private final Set<String> scopes; private RegisteredClient registeredClient; private OAuth2Error error; private boolean redirectOnError;
protected AbstractRequestContext(String authorizationUri, MultiValueMap<String, String> parameters, String clientId, String state, Set<String> scopes) { this.authorizationUri = authorizationUri; this.parameters = parameters; this.clientId = clientId; this.state = state; this.scopes = scopes; }
protected String getAuthorizationUri() { return this.authorizationUri; }
protected MultiValueMap<String, String> getParameters() { return this.parameters; }
protected String getClientId() { return this.clientId; }
protected String getState() { return this.state; }
protected Set<String> getScopes() { return this.scopes; }
protected RegisteredClient getRegisteredClient() { return this.registeredClient; }
protected void setRegisteredClient(RegisteredClient registeredClient) { this.registeredClient = registeredClient; }
protected OAuth2Error getError() { return this.error; }
protected void setError(OAuth2Error error) { this.error = error; }
protected boolean hasError() { return getError() != null; }
protected boolean isRedirectOnError() { return this.redirectOnError; }
protected void setRedirectOnError(boolean redirectOnError) { this.redirectOnError = redirectOnError; }
protected abstract String resolveRedirectUri(); }
private static class OAuth2EndpointUtils {
private OAuth2EndpointUtils() { }
static MultiValueMap<String, String> getParameters(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size()); parameterMap.forEach((key, values) -> { if (values.length > 0) { for (String value : values) { parameters.add(key, value); } } }); return parameters; }
static boolean matchesPkceTokenRequest(HttpServletRequest request) { return AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equals( request.getParameter(OAuth2ParameterNames.GRANT_TYPE)) && request.getParameter(OAuth2ParameterNames.CODE) != null && request.getParameter(PkceParameterNames.CODE_VERIFIER) != null; } }
}
|