Search in sources :

Example 16 with OAuth2Exception

use of org.springframework.security.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationProcessingFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;
    try {
        Authentication authentication = tokenExtractor.extract(request);
        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            Authentication authResult = authenticationManager.authenticate(authentication);
            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }
            eventPublisher.publishAuthenticationSuccess(authResult);
            SecurityContextHolder.getContext().setAuthentication(authResult);
        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();
        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
        authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(failed.getMessage(), failed));
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 17 with OAuth2Exception

use of org.springframework.security.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class AbstractOAuth2SecurityExceptionHandler method doHandle.

protected final void doHandle(HttpServletRequest request, HttpServletResponse response, Exception authException) throws IOException, ServletException {
    try {
        ResponseEntity<OAuth2Exception> result = exceptionTranslator.translate(authException);
        result = enhanceResponse(result, authException);
        exceptionRenderer.handleHttpEntityResponse(result, new ServletWebRequest(request, response));
        response.flushBuffer();
    } catch (ServletException e) {
        // not from an MVC handler so it won't be caught by the dispatcher (even if there is one)
        if (handlerExceptionResolver.resolveException(request, response, this, e) == null) {
            throw e;
        }
    } catch (IOException e) {
        throw e;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        // Wrap other Exceptions. These are not expected to happen
        throw new RuntimeException(e);
    }
}
Also used : ServletException(javax.servlet.ServletException) IOException(java.io.IOException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 18 with OAuth2Exception

use of org.springframework.security.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class DefaultWebResponseExceptionTranslator method handleOAuth2Exception.

private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {
    int status = e.getHttpErrorCode();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cache-Control", "no-store");
    headers.set("Pragma", "no-cache");
    if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
        headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
    }
    ResponseEntity<OAuth2Exception> response = new ResponseEntity<OAuth2Exception>(e, headers, HttpStatus.valueOf(status));
    return response;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) ResponseEntity(org.springframework.http.ResponseEntity) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 19 with OAuth2Exception

use of org.springframework.security.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class OAuth2ClientAuthenticationProcessingFilterTests method testDeniedToken.

@Test
public void testDeniedToken() throws Exception {
    filter.setRestTemplate(restTemplate);
    Mockito.when(restTemplate.getAccessToken()).thenThrow(new OAuth2Exception("User denied acess token"));
    expected.expect(BadCredentialsException.class);
    filter.attemptAuthentication(null, null);
}
Also used : OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) Test(org.junit.Test)

Example 20 with OAuth2Exception

use of org.springframework.security.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class DefaultOAuth2SerializationServiceTests method testExceptionDeserialization.

@Test
public void testExceptionDeserialization() throws Exception {
    Map<String, String> exception = MapBuilder.create("error", "invalid_client").add("error_description", "FOO").build();
    OAuth2Exception result = OAuth2Exception.valueOf(exception);
    // System.err.println(result);
    assertEquals("FOO", result.getMessage());
    assertEquals("invalid_client", result.getOAuth2ErrorCode());
    assertTrue(result instanceof InvalidClientException);
}
Also used : InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) Test(org.junit.Test)

Aggregations

OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)23 Test (org.junit.Test)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)8 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)7 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)6 ClientDetailsService (org.springframework.security.oauth2.provider.ClientDetailsService)6 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)6 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)4 IOException (java.io.IOException)3 Date (java.util.Date)3 OAuth2AccessDeniedException (org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException)3 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)3 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)3 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)3 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)3 ModelAndView (org.springframework.web.servlet.ModelAndView)3 ServletException (javax.servlet.ServletException)2 ResponseEntity (org.springframework.http.ResponseEntity)2 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)2 AccessDeniedException (org.springframework.security.access.AccessDeniedException)2