Search in sources :

Example 6 with OAuth2AccessDeniedException

use of org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationManager method authenticate.

/**
 * Expects the incoming authentication request to have a principal value that is an access token value (e.g. from an
 * authorization header). Loads an authentication from the {@link ResourceServerTokenServices} and checks that the
 * resource id is contained in the {@link AuthorizationRequest} (if one is specified). Also copies authentication
 * details over from the input to the output (e.g. typically so that the access token value and request details can
 * be reported later).
 *
 * @param authentication an authentication request containing an access token value as the principal
 * @return an {@link OAuth2Authentication}
 *
 * @see org.springframework.security.authentication.AuthenticationManager#authenticate(org.springframework.security.core.Authentication)
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        throw new InvalidTokenException("Invalid token (token not found)");
    }
    String token = (String) authentication.getPrincipal();
    OAuth2Authentication auth = tokenServices.loadAuthentication(token);
    if (auth == null) {
        throw new InvalidTokenException("Invalid token: " + token);
    }
    Collection<String> resourceIds = auth.getOAuth2Request().getResourceIds();
    if (resourceId != null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(resourceId)) {
        throw new OAuth2AccessDeniedException("Invalid token does not contain resource id (" + resourceId + ")");
    }
    checkClientDetails(auth);
    if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        // Guard against a cached copy of the same details
        if (!details.equals(auth.getDetails())) {
            // Preserve the authentication details from the one loaded by token services
            details.setDecodedDetails(auth.getDetails());
        }
    }
    auth.setDetails(authentication.getDetails());
    auth.setAuthenticated(true);
    return auth;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 7 with OAuth2AccessDeniedException

use of org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException in project spring-security-oauth by spring-projects.

the class OAuth2ErrorHandler method handleError.

public void handleError(final ClientHttpResponse response) throws IOException {
    if (!HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())) {
        // We should only care about 400 level errors. Ex: A 500 server error shouldn't
        // be an oauth related error.
        errorHandler.handleError(response);
    } else {
        // Need to use buffered response because input stream may need to be consumed multiple times.
        ClientHttpResponse bufferedResponse = new ClientHttpResponse() {

            private byte[] lazyBody;

            public HttpStatus getStatusCode() throws IOException {
                return response.getStatusCode();
            }

            public synchronized InputStream getBody() throws IOException {
                if (lazyBody == null) {
                    InputStream bodyStream = response.getBody();
                    if (bodyStream != null) {
                        lazyBody = FileCopyUtils.copyToByteArray(bodyStream);
                    } else {
                        lazyBody = new byte[0];
                    }
                }
                return new ByteArrayInputStream(lazyBody);
            }

            public HttpHeaders getHeaders() {
                return response.getHeaders();
            }

            public String getStatusText() throws IOException {
                return response.getStatusText();
            }

            public void close() {
                response.close();
            }

            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }
        };
        try {
            HttpMessageConverterExtractor<OAuth2Exception> extractor = new HttpMessageConverterExtractor<OAuth2Exception>(OAuth2Exception.class, messageConverters);
            try {
                OAuth2Exception oauth2Exception = extractor.extractData(bufferedResponse);
                if (oauth2Exception != null) {
                    // gh-875
                    if (oauth2Exception.getClass() == UserDeniedAuthorizationException.class && bufferedResponse.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
                        oauth2Exception = new OAuth2AccessDeniedException(oauth2Exception.getMessage());
                    }
                    // than the header does, so just re-throw it here.
                    throw oauth2Exception;
                }
            } catch (RestClientException e) {
            // ignore
            } catch (HttpMessageConversionException e) {
            // ignore
            }
            // first try: www-authenticate error
            List<String> authenticateHeaders = bufferedResponse.getHeaders().get("WWW-Authenticate");
            if (authenticateHeaders != null) {
                for (String authenticateHeader : authenticateHeaders) {
                    maybeThrowExceptionFromHeader(authenticateHeader, OAuth2AccessToken.BEARER_TYPE);
                    maybeThrowExceptionFromHeader(authenticateHeader, OAuth2AccessToken.OAUTH2_TYPE);
                }
            }
            // then delegate to the custom handler
            errorHandler.handleError(bufferedResponse);
        } catch (InvalidTokenException ex) {
            // Special case: an invalid token can be renewed so tell the caller what to do
            throw new AccessTokenRequiredException(resource);
        } catch (OAuth2Exception ex) {
            if (!ex.getClass().equals(OAuth2Exception.class)) {
                // rethrow
                throw ex;
            }
            // This is not an exception that is really understood, so allow our delegate
            // to handle it in a non-oauth way
            errorHandler.handleError(bufferedResponse);
        }
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) UserDeniedAuthorizationException(org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpMessageConversionException(org.springframework.http.converter.HttpMessageConversionException) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Aggregations

OAuth2AccessDeniedException (org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException)6 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)3 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)3 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)2 OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)2 ResponseExtractor (org.springframework.web.client.ResponseExtractor)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 URI (java.net.URI)1 Test (org.junit.Test)1 HttpHeaders (org.springframework.http.HttpHeaders)1 ResponseEntity (org.springframework.http.ResponseEntity)1 HttpMessageConversionException (org.springframework.http.converter.HttpMessageConversionException)1 OAuth2RestTemplate (org.springframework.security.oauth2.client.OAuth2RestTemplate)1 AccessTokenRequiredException (org.springframework.security.oauth2.client.http.AccessTokenRequiredException)1 UserRedirectRequiredException (org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)1 OAuth2ContextConfiguration (org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration)1 AccessTokenRequest (org.springframework.security.oauth2.client.token.AccessTokenRequest)1 ResourceOwnerPasswordResourceDetails (org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails)1 UserDeniedAuthorizationException (org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException)1