From ba19a9e4b6d65050c6e9520801f98c6f4975d5fa Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 31 Jul 2020 22:28:23 -0700 Subject: [PATCH] Polish spring-security-oauth2-resource-server main code Manually polish `spring-security-oauth-resource-server` following the formatting and checkstyle fixes. Issue gh-8945 --- .../BearerTokenAuthenticationToken.java | 10 +------- .../server/resource/BearerTokenError.java | 2 -- .../server/resource/BearerTokenErrors.java | 12 ++++----- ...bstractOAuth2TokenAuthenticationToken.java | 6 ----- .../BearerTokenAuthentication.java | 6 +---- .../JwtAuthenticationConverter.java | 1 - .../JwtAuthenticationProvider.java | 18 ++++++------- .../JwtAuthenticationToken.java | 3 --- ...JwtBearerTokenAuthenticationConverter.java | 2 -- .../JwtGrantedAuthoritiesConverter.java | 11 ++------ ...ReactiveAuthenticationManagerResolver.java | 5 +--- .../JwtReactiveAuthenticationManager.java | 5 +--- .../OpaqueTokenAuthenticationProvider.java | 16 ++++++------ ...queTokenReactiveAuthenticationManager.java | 5 +--- .../NimbusOpaqueTokenIntrospector.java | 12 --------- ...NimbusReactiveOpaqueTokenIntrospector.java | 10 ++------ ...h2IntrospectionAuthenticatedPrincipal.java | 8 ------ .../BearerTokenAuthenticationEntryPoint.java | 15 ----------- .../web/BearerTokenAuthenticationFilter.java | 17 +------------ .../web/DefaultBearerTokenResolver.java | 25 +++++++------------ .../BearerTokenAccessDeniedHandler.java | 8 ------ .../BearerTokenServerAccessDeniedHandler.java | 5 ---- .../ServerBearerExchangeFilterFunction.java | 3 --- .../ServletBearerExchangeFilterFunction.java | 3 --- ...erTokenServerAuthenticationEntryPoint.java | 9 ------- ...verBearerTokenAuthenticationConverter.java | 20 +++++++-------- 26 files changed, 48 insertions(+), 189 deletions(-) diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java index a1b6ecc0e7..940ee7b676 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java @@ -40,7 +40,7 @@ public class BearerTokenAuthenticationToken extends AbstractAuthenticationToken private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - private String token; + private final String token; /** * Create a {@code BearerTokenAuthenticationToken} using the provided parameter(s) @@ -48,9 +48,7 @@ public class BearerTokenAuthenticationToken extends AbstractAuthenticationToken */ public BearerTokenAuthenticationToken(String token) { super(Collections.emptyList()); - Assert.hasText(token, "token cannot be empty"); - this.token = token; } @@ -65,17 +63,11 @@ public class BearerTokenAuthenticationToken extends AbstractAuthenticationToken return this.token; } - /** - * {@inheritDoc} - */ @Override public Object getCredentials() { return this.getToken(); } - /** - * {@inheritDoc} - */ @Override public Object getPrincipal() { return this.getToken(); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenError.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenError.java index 0fa0463d5c..ef97c711c0 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenError.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenError.java @@ -59,7 +59,6 @@ public final class BearerTokenError extends OAuth2Error { String scope) { super(errorCode, description, errorUri); Assert.notNull(httpStatus, "httpStatus cannot be null"); - Assert.isTrue(isDescriptionValid(description), "description contains invalid ASCII characters, it must conform to RFC 6750"); Assert.isTrue(isErrorCodeValid(errorCode), @@ -67,7 +66,6 @@ public final class BearerTokenError extends OAuth2Error { Assert.isTrue(isErrorUriValid(errorUri), "errorUri contains invalid ASCII characters, it must conform to RFC 6750"); Assert.isTrue(isScopeValid(scope), "scope contains invalid ASCII characters, it must conform to RFC 6750"); - this.httpStatus = httpStatus; this.scope = scope; } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java index 357cefe7dd..eaa90b8692 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java @@ -36,6 +36,9 @@ public final class BearerTokenErrors { private static final String DEFAULT_URI = "https://tools.ietf.org/html/rfc6750#section-3.1"; + private BearerTokenErrors() { + } + /** * Create a {@link BearerTokenError} caused by an invalid request * @param message a description of the error @@ -46,7 +49,7 @@ public final class BearerTokenErrors { return new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, message, DEFAULT_URI); } - catch (IllegalArgumentException malformed) { + catch (IllegalArgumentException ex) { // some third-party library error messages are not suitable for RFC 6750's // error message charset return DEFAULT_INVALID_REQUEST; @@ -63,7 +66,7 @@ public final class BearerTokenErrors { return new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, message, DEFAULT_URI); } - catch (IllegalArgumentException malformed) { + catch (IllegalArgumentException ex) { // some third-party library error messages are not suitable for RFC 6750's // error message charset return DEFAULT_INVALID_TOKEN; @@ -80,14 +83,11 @@ public final class BearerTokenErrors { return new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN, message, DEFAULT_URI, scope); } - catch (IllegalArgumentException malformed) { + catch (IllegalArgumentException ex) { // some third-party library error messages are not suitable for RFC 6750's // error message charset return DEFAULT_INSUFFICIENT_SCOPE; } } - private BearerTokenErrors() { - } - } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/AbstractOAuth2TokenAuthenticationToken.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/AbstractOAuth2TokenAuthenticationToken.java index 8992f5be8d..d221136802 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/AbstractOAuth2TokenAuthenticationToken.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/AbstractOAuth2TokenAuthenticationToken.java @@ -84,17 +84,11 @@ public abstract class AbstractOAuth2TokenAuthenticationToken attributes; + private final Map attributes; /** * Constructs a {@link BearerTokenAuthentication} with the provided arguments @@ -50,7 +50,6 @@ public class BearerTokenAuthentication extends AbstractOAuth2TokenAuthentication */ public BearerTokenAuthentication(OAuth2AuthenticatedPrincipal principal, OAuth2AccessToken credentials, Collection authorities) { - super(credentials, principal, credentials, authorities); Assert.isTrue(credentials.getTokenType() == OAuth2AccessToken.TokenType.BEARER, "credentials must be a bearer token"); @@ -58,9 +57,6 @@ public class BearerTokenAuthentication extends AbstractOAuth2TokenAuthentication setAuthenticated(true); } - /** - * {@inheritDoc} - */ @Override public Map getTokenAttributes() { return this.attributes; diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java index 9cd153f925..1962e03aac 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java @@ -43,7 +43,6 @@ public class JwtAuthenticationConverter implements Converter authentication) { return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication); @@ -108,7 +105,6 @@ public final class JwtAuthenticationProvider implements AuthenticationProvider { public void setJwtAuthenticationConverter( Converter jwtAuthenticationConverter) { - Assert.notNull(jwtAuthenticationConverter, "jwtAuthenticationConverter cannot be null"); this.jwtAuthenticationConverter = jwtAuthenticationConverter; } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationToken.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationToken.java index 7745a17a57..e389e5e93c 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationToken.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationToken.java @@ -72,9 +72,6 @@ public class JwtAuthenticationToken extends AbstractOAuth2TokenAuthenticationTok this.name = name; } - /** - * {@inheritDoc} - */ @Override public Map getTokenAttributes() { return this.getToken().getClaims(); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtBearerTokenAuthenticationConverter.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtBearerTokenAuthenticationConverter.java index 726c98a61a..f548c8ac2c 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtBearerTokenAuthenticationConverter.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtBearerTokenAuthenticationConverter.java @@ -52,10 +52,8 @@ public final class JwtBearerTokenAuthenticationConverter implements Converter attributes = jwt.getClaims(); - AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt); Collection authorities = token.getAuthorities(); - OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, authorities); return new BearerTokenAuthentication(principal, accessToken, authorities); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter.java index 0e800a6d95..d126984a21 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter.java @@ -84,11 +84,9 @@ public final class JwtGrantedAuthoritiesConverter implements Converter getAuthorities(Jwt jwt) { String claimName = getAuthoritiesClaimName(jwt); - if (claimName == null) { return Collections.emptyList(); } - Object authorities = jwt.getClaim(claimName); if (authorities instanceof String) { if (StringUtils.hasText((String) authorities)) { return Arrays.asList(((String) authorities).split(" ")); } - else { - return Collections.emptyList(); - } + return Collections.emptyList(); } - else if (authorities instanceof Collection) { + if (authorities instanceof Collection) { return (Collection) authorities; } - return Collections.emptyList(); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java index e4741235e3..701c9c4b34 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java @@ -110,7 +110,6 @@ public final class JwtIssuerReactiveAuthenticationManagerResolver */ public JwtIssuerReactiveAuthenticationManagerResolver( ReactiveAuthenticationManagerResolver issuerAuthenticationManagerResolver) { - Assert.notNull(issuerAuthenticationManagerResolver, "issuerAuthenticationManagerResolver cannot be null"); this.issuerAuthenticationManagerResolver = issuerAuthenticationManagerResolver; } @@ -141,9 +140,7 @@ public final class JwtIssuerReactiveAuthenticationManagerResolver if (issuer == null) { throw new InvalidBearerTokenException("Missing issuer"); } - else { - return issuer; - } + return issuer; } catch (Exception ex) { throw new InvalidBearerTokenException(ex.getMessage(), ex); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManager.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManager.java index 4b8641f323..2cf613c783 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManager.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManager.java @@ -65,7 +65,6 @@ public final class JwtReactiveAuthenticationManager implements ReactiveAuthentic */ public void setJwtAuthenticationConverter( Converter> jwtAuthenticationConverter) { - Assert.notNull(jwtAuthenticationConverter, "jwtAuthenticationConverter cannot be null"); this.jwtAuthenticationConverter = jwtAuthenticationConverter; } @@ -74,9 +73,7 @@ public final class JwtReactiveAuthenticationManager implements ReactiveAuthentic if (ex instanceof BadJwtException) { return new InvalidBearerTokenException(ex.getMessage(), ex); } - else { - return new AuthenticationServiceException(ex.getMessage(), ex); - } + return new AuthenticationServiceException(ex.getMessage(), ex); } } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java index ff96d7a279..6554f2b0bb 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java @@ -86,10 +86,15 @@ public final class OpaqueTokenAuthenticationProvider implements AuthenticationPr return null; } BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication; + OAuth2AuthenticatedPrincipal principal = getOAuth2AuthenticatedPrincipal(bearer); + AbstractAuthenticationToken result = convert(principal, bearer.getToken()); + result.setDetails(bearer.getDetails()); + return result; + } - OAuth2AuthenticatedPrincipal principal; + private OAuth2AuthenticatedPrincipal getOAuth2AuthenticatedPrincipal(BearerTokenAuthenticationToken bearer) { try { - principal = this.introspector.introspect(bearer.getToken()); + return this.introspector.introspect(bearer.getToken()); } catch (BadOpaqueTokenException failed) { throw new InvalidBearerTokenException(failed.getMessage()); @@ -97,15 +102,8 @@ public final class OpaqueTokenAuthenticationProvider implements AuthenticationPr catch (OAuth2IntrospectionException failed) { throw new AuthenticationServiceException(failed.getMessage()); } - - AbstractAuthenticationToken result = convert(principal, bearer.getToken()); - result.setDetails(bearer.getDetails()); - return result; } - /** - * {@inheritDoc} - */ @Override public boolean supports(Class authentication) { return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java index dfd7fbd211..679e44fa2a 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java @@ -84,7 +84,6 @@ public class OpaqueTokenReactiveAuthenticationManager implements ReactiveAuthent return this.introspector.introspect(token).map((principal) -> { Instant iat = principal.getAttribute(OAuth2IntrospectionClaimNames.ISSUED_AT); Instant exp = principal.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT); - // construct token OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, token, iat, exp); return new BearerTokenAuthentication(principal, accessToken, principal.getAuthorities()); @@ -95,9 +94,7 @@ public class OpaqueTokenReactiveAuthenticationManager implements ReactiveAuthent if (ex instanceof BadOpaqueTokenException) { return new InvalidBearerTokenException(ex.getMessage(), ex); } - else { - return new AuthenticationServiceException(ex.getMessage(), ex); - } + return new AuthenticationServiceException(ex.getMessage(), ex); } } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java index bbeae6fe85..a1d427712f 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java @@ -74,7 +74,6 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { Assert.notNull(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(clientId, "clientId cannot be null"); Assert.notNull(clientSecret, "clientSecret cannot be null"); - this.requestEntityConverter = this.defaultRequestEntityConverter(URI.create(introspectionUri)); RestTemplate restTemplate = new RestTemplate(); restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(clientId, clientSecret)); @@ -92,7 +91,6 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { public NimbusOpaqueTokenIntrospector(String introspectionUri, RestOperations restOperations) { Assert.notNull(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(restOperations, "restOperations cannot be null"); - this.requestEntityConverter = this.defaultRequestEntityConverter(URI.create(introspectionUri)); this.restOperations = restOperations; } @@ -117,27 +115,21 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { return body; } - /** - * {@inheritDoc} - */ @Override public OAuth2AuthenticatedPrincipal introspect(String token) { RequestEntity requestEntity = this.requestEntityConverter.convert(token); if (requestEntity == null) { throw new OAuth2IntrospectionException("requestEntityConverter returned a null entity"); } - ResponseEntity responseEntity = makeRequest(requestEntity); HTTPResponse httpResponse = adaptToNimbusResponse(responseEntity); TokenIntrospectionResponse introspectionResponse = parseNimbusResponse(httpResponse); TokenIntrospectionSuccessResponse introspectionSuccessResponse = castToNimbusSuccess(introspectionResponse); - // relying solely on the authorization server to validate this token (not checking // 'exp', for example) if (!introspectionSuccessResponse.isActive()) { throw new BadOpaqueTokenException("Provided token isn't active"); } - return convertClaimsSet(introspectionSuccessResponse); } @@ -149,7 +141,6 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { */ public void setRequestEntityConverter(Converter> requestEntityConverter) { Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null"); - this.requestEntityConverter = requestEntityConverter; } @@ -166,7 +157,6 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { HTTPResponse response = new HTTPResponse(responseEntity.getStatusCodeValue()); response.setHeader(HttpHeaders.CONTENT_TYPE, responseEntity.getHeaders().getContentType().toString()); response.setContent(responseEntity.getBody()); - if (response.getStatusCode() != HTTPResponse.SC_OK) { throw new OAuth2IntrospectionException("Introspection endpoint responded with " + response.getStatusCode()); } @@ -219,12 +209,10 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { if (response.getScope() != null) { List scopes = Collections.unmodifiableList(response.getScope().toStringList()); claims.put(OAuth2IntrospectionClaimNames.SCOPE, scopes); - for (String scope : scopes) { authorities.add(new SimpleGrantedAuthority(this.authorityPrefix + scope)); } } - return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java index 5a6603b8a0..28eca19b62 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java @@ -54,9 +54,9 @@ import org.springframework.web.reactive.function.client.WebClient; */ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector { - private URI introspectionUri; + private final URI introspectionUri; - private WebClient webClient; + private final WebClient webClient; private String authorityPrefix = "SCOPE_"; @@ -71,7 +71,6 @@ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueToke Assert.hasText(introspectionUri, "introspectionUri cannot be empty"); Assert.hasText(clientId, "clientId cannot be empty"); Assert.notNull(clientSecret, "clientSecret cannot be null"); - this.introspectionUri = URI.create(introspectionUri); this.webClient = WebClient.builder().defaultHeaders((h) -> h.setBasicAuth(clientId, clientSecret)).build(); } @@ -85,14 +84,10 @@ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueToke public NimbusReactiveOpaqueTokenIntrospector(String introspectionUri, WebClient webClient) { Assert.hasText(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(webClient, "webClient cannot be null"); - this.introspectionUri = URI.create(introspectionUri); this.webClient = webClient; } - /** - * {@inheritDoc} - */ @Override public Mono introspect(String token) { return Mono.just(token).flatMap(this::makeRequest).flatMap(this::adaptToNimbusResponse) @@ -177,7 +172,6 @@ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueToke authorities.add(new SimpleGrantedAuthority(this.authorityPrefix + scope)); } } - return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipal.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipal.java index 338ff3ec56..08ec004143 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipal.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipal.java @@ -45,7 +45,6 @@ public final class OAuth2IntrospectionAuthenticatedPrincipal */ public OAuth2IntrospectionAuthenticatedPrincipal(Map attributes, Collection authorities) { - this.delegate = new DefaultOAuth2AuthenticatedPrincipal(attributes, authorities); } @@ -58,7 +57,6 @@ public final class OAuth2IntrospectionAuthenticatedPrincipal */ public OAuth2IntrospectionAuthenticatedPrincipal(String name, Map attributes, Collection authorities) { - this.delegate = new DefaultOAuth2AuthenticatedPrincipal(name, attributes, authorities); } @@ -81,17 +79,11 @@ public final class OAuth2IntrospectionAuthenticatedPrincipal return this.delegate.getAuthorities(); } - /** - * {@inheritDoc} - */ @Override public String getName() { return this.delegate.getName(); } - /** - * {@inheritDoc} - */ @Override public Map getClaims() { return getAttributes(); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java index b92d88ac19..f28cdd2c3b 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java @@ -59,41 +59,29 @@ public final class BearerTokenAuthenticationEntryPoint implements Authentication @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { - HttpStatus status = HttpStatus.UNAUTHORIZED; - Map parameters = new LinkedHashMap<>(); - if (this.realmName != null) { parameters.put("realm", this.realmName); } - if (authException instanceof OAuth2AuthenticationException) { OAuth2Error error = ((OAuth2AuthenticationException) authException).getError(); - parameters.put("error", error.getErrorCode()); - if (StringUtils.hasText(error.getDescription())) { parameters.put("error_description", error.getDescription()); } - if (StringUtils.hasText(error.getUri())) { parameters.put("error_uri", error.getUri()); } - if (error instanceof BearerTokenError) { BearerTokenError bearerTokenError = (BearerTokenError) error; - if (StringUtils.hasText(bearerTokenError.getScope())) { parameters.put("scope", bearerTokenError.getScope()); } - status = ((BearerTokenError) error).getHttpStatus(); } } - String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters); - response.addHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); response.setStatus(status.value()); } @@ -109,20 +97,17 @@ public final class BearerTokenAuthenticationEntryPoint implements Authentication private static String computeWWWAuthenticateHeaderValue(Map parameters) { StringBuilder wwwAuthenticate = new StringBuilder(); wwwAuthenticate.append("Bearer"); - if (!parameters.isEmpty()) { wwwAuthenticate.append(" "); int i = 0; for (Map.Entry entry : parameters.entrySet()) { wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); - if (i != parameters.size() - 1) { wwwAuthenticate.append(", "); } i++; } } - return wwwAuthenticate.toString(); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java index 4abad2a8df..e69618545e 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java @@ -74,7 +74,6 @@ public final class BearerTokenAuthenticationFilter extends OncePerRequestFilter */ public BearerTokenAuthenticationFilter( AuthenticationManagerResolver authenticationManagerResolver) { - Assert.notNull(authenticationManagerResolver, "authenticationManagerResolver cannot be null"); this.authenticationManagerResolver = authenticationManagerResolver; } @@ -101,11 +100,7 @@ public final class BearerTokenAuthenticationFilter extends OncePerRequestFilter @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - - final boolean debug = this.logger.isDebugEnabled(); - String token; - try { token = this.bearerTokenResolver.resolve(request); } @@ -113,33 +108,23 @@ public final class BearerTokenAuthenticationFilter extends OncePerRequestFilter this.authenticationEntryPoint.commence(request, response, invalid); return; } - if (token == null) { filterChain.doFilter(request, response); return; } - BearerTokenAuthenticationToken authenticationRequest = new BearerTokenAuthenticationToken(token); - authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); - try { AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request); Authentication authenticationResult = authenticationManager.authenticate(authenticationRequest); - SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authenticationResult); SecurityContextHolder.setContext(context); - filterChain.doFilter(request, response); } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); - - if (debug) { - this.logger.debug("Authentication request for failed!", failed); - } - + this.logger.debug("Authentication request for failed!", failed); this.authenticationFailureHandler.onAuthenticationFailure(request, response, failed); } } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java index aea2208569..db2fd78187 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java @@ -46,9 +46,6 @@ public final class DefaultBearerTokenResolver implements BearerTokenResolver { private String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION; - /** - * {@inheritDoc} - */ @Override public String resolve(HttpServletRequest request) { String authorizationHeaderToken = resolveFromAuthorizationHeader(request); @@ -61,7 +58,7 @@ public final class DefaultBearerTokenResolver implements BearerTokenResolver { } return authorizationHeaderToken; } - else if (parameterToken != null && isParameterTokenSupportedForRequest(request)) { + if (parameterToken != null && isParameterTokenSupportedForRequest(request)) { return parameterToken; } return null; @@ -104,17 +101,15 @@ public final class DefaultBearerTokenResolver implements BearerTokenResolver { private String resolveFromAuthorizationHeader(HttpServletRequest request) { String authorization = request.getHeader(this.bearerTokenHeaderName); - if (StringUtils.startsWithIgnoreCase(authorization, "bearer")) { - Matcher matcher = authorizationPattern.matcher(authorization); - - if (!matcher.matches()) { - BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed"); - throw new OAuth2AuthenticationException(error); - } - - return matcher.group("token"); + if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) { + return null; } - return null; + Matcher matcher = authorizationPattern.matcher(authorization); + if (!matcher.matches()) { + BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed"); + throw new OAuth2AuthenticationException(error); + } + return matcher.group("token"); } private static String resolveFromRequestParameters(HttpServletRequest request) { @@ -122,11 +117,9 @@ public final class DefaultBearerTokenResolver implements BearerTokenResolver { if (values == null || values.length == 0) { return null; } - if (values.length == 1) { return values[0]; } - BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java index 452f940d8c..043412492f 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java @@ -59,22 +59,17 @@ public final class BearerTokenAccessDeniedHandler implements AccessDeniedHandler @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) { - Map parameters = new LinkedHashMap<>(); - if (this.realmName != null) { parameters.put("realm", this.realmName); } - if (request.getUserPrincipal() instanceof AbstractOAuth2TokenAuthenticationToken) { parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE); parameters.put("error_description", "The request requires higher privileges than provided by the access token."); parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1"); } - String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters); - response.addHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); response.setStatus(HttpStatus.FORBIDDEN.value()); } @@ -90,20 +85,17 @@ public final class BearerTokenAccessDeniedHandler implements AccessDeniedHandler private static String computeWWWAuthenticateHeaderValue(Map parameters) { StringBuilder wwwAuthenticate = new StringBuilder(); wwwAuthenticate.append("Bearer"); - if (!parameters.isEmpty()) { wwwAuthenticate.append(" "); int i = 0; for (Map.Entry entry : parameters.entrySet()) { wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); - if (i != parameters.size() - 1) { wwwAuthenticate.append(", "); } i++; } } - return wwwAuthenticate.toString(); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandler.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandler.java index a6b7884de0..3c07c3892a 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandler.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandler.java @@ -55,13 +55,10 @@ public class BearerTokenServerAccessDeniedHandler implements ServerAccessDeniedH @Override public Mono handle(ServerWebExchange exchange, AccessDeniedException denied) { - Map parameters = new LinkedHashMap<>(); - if (this.realmName != null) { parameters.put("realm", this.realmName); } - return exchange.getPrincipal().filter(AbstractOAuth2TokenAuthenticationToken.class::isInstance) .map((token) -> errorMessageParameters(parameters)).switchIfEmpty(Mono.just(parameters)) .flatMap((params) -> respond(exchange, params)); @@ -80,7 +77,6 @@ public class BearerTokenServerAccessDeniedHandler implements ServerAccessDeniedH parameters.put("error_description", "The request requires higher privileges than provided by the access token."); parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1"); - return parameters; } @@ -105,7 +101,6 @@ public class BearerTokenServerAccessDeniedHandler implements ServerAccessDeniedH i++; } } - return wwwAuthenticate.toString(); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.java index 19d4839f1e..edb902bbee 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.java @@ -51,9 +51,6 @@ import org.springframework.web.reactive.function.client.ExchangeFunction; */ public final class ServerBearerExchangeFilterFunction implements ExchangeFilterFunction { - /** - * {@inheritDoc} - */ @Override public Mono filter(ClientRequest request, ExchangeFunction next) { return oauth2Token().map((token) -> bearer(request, token)).defaultIfEmpty(request).flatMap(next::exchange); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.java index 556c326cdd..f6a34f21c6 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.java @@ -62,9 +62,6 @@ public final class ServletBearerExchangeFilterFunction implements ExchangeFilter static final String SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY = "org.springframework.security.SECURITY_CONTEXT_ATTRIBUTES"; - /** - * {@inheritDoc} - */ @Override public Mono filter(ClientRequest request, ExchangeFunction next) { return oauth2Token().map((token) -> bearer(request, token)).defaultIfEmpty(request).flatMap(next::exchange); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/BearerTokenServerAuthenticationEntryPoint.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/BearerTokenServerAuthenticationEntryPoint.java index 3e8ded5d9c..167fa10c0b 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/BearerTokenServerAuthenticationEntryPoint.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/BearerTokenServerAuthenticationEntryPoint.java @@ -59,7 +59,6 @@ public final class BearerTokenServerAuthenticationEntryPoint implements ServerAu public Mono commence(ServerWebExchange exchange, AuthenticationException authException) { return Mono.defer(() -> { HttpStatus status = getStatus(authException); - Map parameters = createParameters(authException); String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters); ServerHttpResponse response = exchange.getResponse(); @@ -74,23 +73,17 @@ public final class BearerTokenServerAuthenticationEntryPoint implements ServerAu if (this.realmName != null) { parameters.put("realm", this.realmName); } - if (authException instanceof OAuth2AuthenticationException) { OAuth2Error error = ((OAuth2AuthenticationException) authException).getError(); - parameters.put("error", error.getErrorCode()); - if (StringUtils.hasText(error.getDescription())) { parameters.put("error_description", error.getDescription()); } - if (StringUtils.hasText(error.getUri())) { parameters.put("error_uri", error.getUri()); } - if (error instanceof BearerTokenError) { BearerTokenError bearerTokenError = (BearerTokenError) error; - if (StringUtils.hasText(bearerTokenError.getScope())) { parameters.put("scope", bearerTokenError.getScope()); } @@ -112,7 +105,6 @@ public final class BearerTokenServerAuthenticationEntryPoint implements ServerAu private static String computeWWWAuthenticateHeaderValue(Map parameters) { StringBuilder wwwAuthenticate = new StringBuilder(); wwwAuthenticate.append("Bearer"); - if (!parameters.isEmpty()) { wwwAuthenticate.append(" "); int i = 0; @@ -124,7 +116,6 @@ public final class BearerTokenServerAuthenticationEntryPoint implements ServerAu i++; } } - return wwwAuthenticate.toString(); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverter.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverter.java index dff1306dba..e4d3d6dfc9 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverter.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverter.java @@ -74,7 +74,7 @@ public class ServerBearerTokenAuthenticationConverter implements ServerAuthentic } return authorizationHeaderToken; } - else if (parameterToken != null && isParameterTokenSupportedForRequest(request)) { + if (parameterToken != null && isParameterTokenSupportedForRequest(request)) { return parameterToken; } return null; @@ -107,17 +107,15 @@ public class ServerBearerTokenAuthenticationConverter implements ServerAuthentic private String resolveFromAuthorizationHeader(HttpHeaders headers) { String authorization = headers.getFirst(this.bearerTokenHeaderName); - if (StringUtils.startsWithIgnoreCase(authorization, "bearer")) { - Matcher matcher = authorizationPattern.matcher(authorization); - - if (!matcher.matches()) { - BearerTokenError error = invalidTokenError(); - throw new OAuth2AuthenticationException(error); - } - - return matcher.group("token"); + if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) { + return null; } - return null; + Matcher matcher = authorizationPattern.matcher(authorization); + if (!matcher.matches()) { + BearerTokenError error = invalidTokenError(); + throw new OAuth2AuthenticationException(error); + } + return matcher.group("token"); } private static BearerTokenError invalidTokenError() {