Search in sources :

Example 51 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class BearerTokenAuthenticationFilterTests method doFilterWhenAuthenticationFailsWithCustomHandlerThenPropagatesError.

@Test
public void doFilterWhenAuthenticationFailsWithCustomHandlerThenPropagatesError() throws ServletException, IOException {
    BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, "description", "uri");
    OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
    given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
    given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception);
    BearerTokenAuthenticationFilter filter = addMocks(new BearerTokenAuthenticationFilter(this.authenticationManager));
    filter.setAuthenticationFailureHandler(this.authenticationFailureHandler);
    filter.doFilter(this.request, this.response, this.filterChain);
    verify(this.authenticationFailureHandler).onAuthenticationFailure(this.request, this.response, exception);
}
Also used : BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 52 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class BearerTokenAuthenticationEntryPoint method commence.

/**
 * Collect error details from the provided parameters and format according to RFC
 * 6750, specifically {@code error}, {@code error_description}, {@code error_uri}, and
 * {@code scope}.
 * @param request that resulted in an <code>AuthenticationException</code>
 * @param response so that the user agent can begin authentication
 * @param authException that caused the invocation
 */
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
    HttpStatus status = HttpStatus.UNAUTHORIZED;
    Map<String, String> 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());
}
Also used : HttpStatus(org.springframework.http.HttpStatus) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) LinkedHashMap(java.util.LinkedHashMap)

Example 53 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class BearerTokenAuthenticationFilter method doFilterInternal.

/**
 * Extract any
 * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer
 * Token</a> from the request and attempt an authentication.
 * @param request
 * @param response
 * @param filterChain
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String token;
    try {
        token = this.bearerTokenResolver.resolve(request);
    } catch (OAuth2AuthenticationException invalid) {
        this.logger.trace("Sending to authentication entry point since failed to resolve bearer token", invalid);
        this.authenticationEntryPoint.commence(request, response, invalid);
        return;
    }
    if (token == null) {
        this.logger.trace("Did not process request since did not find bearer token");
        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);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authenticationResult));
        }
        filterChain.doFilter(request, response);
    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();
        this.logger.trace("Failed to process authentication request", failed);
        this.authenticationFailureHandler.onAuthenticationFailure(request, response, failed);
    }
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken)

Example 54 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class DefaultBearerTokenResolver method resolve.

@Override
public String resolve(final HttpServletRequest request) {
    final String authorizationHeaderToken = resolveFromAuthorizationHeader(request);
    final String parameterToken = isParameterTokenSupportedForRequest(request) ? resolveFromRequestParameters(request) : null;
    if (authorizationHeaderToken != null) {
        if (parameterToken != null) {
            final BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request");
            throw new OAuth2AuthenticationException(error);
        }
        return authorizationHeaderToken;
    }
    if (parameterToken != null && isParameterTokenEnabledForRequest(request)) {
        return parameterToken;
    }
    return null;
}
Also used : BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 55 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class DefaultBearerTokenResolver method resolveFromAuthorizationHeader.

private String resolveFromAuthorizationHeader(HttpServletRequest request) {
    String authorization = request.getHeader(this.bearerTokenHeaderName);
    if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
        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");
}
Also used : Matcher(java.util.regex.Matcher) BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Aggregations

OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)52 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)31 Test (org.junit.jupiter.api.Test)27 BearerTokenError (org.springframework.security.oauth2.server.resource.BearerTokenError)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)9 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)8 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)7 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)7 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)7 Map (java.util.Map)6 Authentication (org.springframework.security.core.Authentication)6 AuthenticationException (org.springframework.security.core.AuthenticationException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)6 Mono (reactor.core.publisher.Mono)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Base64 (java.util.Base64)5