Search in sources :

Example 1 with AccessTokenRequiredException

use of org.springframework.security.oauth2.client.http.AccessTokenRequiredException in project spring-security-oauth by spring-projects.

the class DefaultOAuth2RequestAuthenticator method authenticate.

@Override
public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext, ClientHttpRequest request) {
    OAuth2AccessToken accessToken = clientContext.getAccessToken();
    if (accessToken == null) {
        throw new AccessTokenRequiredException(resource);
    }
    String tokenType = accessToken.getTokenType();
    if (!StringUtils.hasText(tokenType)) {
        // we'll assume basic bearer token type if none is specified.
        tokenType = OAuth2AccessToken.BEARER_TYPE;
    }
    request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue()));
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AccessTokenRequiredException(org.springframework.security.oauth2.client.http.AccessTokenRequiredException)

Example 2 with AccessTokenRequiredException

use of org.springframework.security.oauth2.client.http.AccessTokenRequiredException in project spring-security-oauth by spring-projects.

the class OAuth2RestTemplate method acquireAccessToken.

protected OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context) throws UserRedirectRequiredException {
    AccessTokenRequest accessTokenRequest = oauth2Context.getAccessTokenRequest();
    if (accessTokenRequest == null) {
        throw new AccessTokenRequiredException("No OAuth 2 security context has been established. Unable to access resource '" + this.resource.getId() + "'.", resource);
    }
    // Transfer the preserved state from the (longer lived) context to the current request.
    String stateKey = accessTokenRequest.getStateKey();
    if (stateKey != null) {
        accessTokenRequest.setPreservedState(oauth2Context.removePreservedState(stateKey));
    }
    OAuth2AccessToken existingToken = oauth2Context.getAccessToken();
    if (existingToken != null) {
        accessTokenRequest.setExistingToken(existingToken);
    }
    OAuth2AccessToken accessToken = null;
    accessToken = accessTokenProvider.obtainAccessToken(resource, accessTokenRequest);
    if (accessToken == null || accessToken.getValue() == null) {
        throw new IllegalStateException("Access token provider returned a null access token, which is illegal according to the contract.");
    }
    oauth2Context.setAccessToken(accessToken);
    return accessToken;
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AccessTokenRequiredException(org.springframework.security.oauth2.client.http.AccessTokenRequiredException) AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest)

Example 3 with AccessTokenRequiredException

use of org.springframework.security.oauth2.client.http.AccessTokenRequiredException 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 response.getRawStatusCode();
            }
        };
        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)

Example 4 with AccessTokenRequiredException

use of org.springframework.security.oauth2.client.http.AccessTokenRequiredException in project spring-security-oauth by spring-projects.

the class OAuth2ErrorHandler method maybeThrowExceptionFromHeader.

private void maybeThrowExceptionFromHeader(String authenticateHeader, String headerType) {
    headerType = headerType.toLowerCase();
    if (authenticateHeader.toLowerCase().startsWith(headerType)) {
        Map<String, String> headerEntries = StringSplitUtils.splitEachArrayElementAndCreateMap(StringSplitUtils.splitIgnoringQuotes(authenticateHeader.substring(headerType.length()), ','), "=", "\"");
        OAuth2Exception ex = OAuth2Exception.valueOf(headerEntries);
        if (ex instanceof InvalidTokenException) {
            // Special case: an invalid token can be renewed so tell the caller what to do
            throw new AccessTokenRequiredException(resource);
        }
        throw ex;
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 5 with AccessTokenRequiredException

use of org.springframework.security.oauth2.client.http.AccessTokenRequiredException in project spring-security-oauth by spring-projects.

the class OAuth2RestTemplate method doExecute.

@Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException {
    OAuth2AccessToken accessToken = context.getAccessToken();
    RuntimeException rethrow = null;
    try {
        return super.doExecute(url, method, requestCallback, responseExtractor);
    } catch (AccessTokenRequiredException e) {
        rethrow = e;
    } catch (OAuth2AccessDeniedException e) {
        rethrow = e;
    } catch (InvalidTokenException e) {
        // Don't reveal the token value in case it is logged
        rethrow = new OAuth2AccessDeniedException("Invalid token for client=" + getClientId());
    }
    if (accessToken != null && retryBadAccessTokens) {
        context.setAccessToken(null);
        try {
            return super.doExecute(url, method, requestCallback, responseExtractor);
        } catch (InvalidTokenException e) {
            // Don't reveal the token value in case it is logged
            rethrow = new OAuth2AccessDeniedException("Invalid token for client=" + getClientId());
        }
    }
    throw rethrow;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AccessTokenRequiredException(org.springframework.security.oauth2.client.http.AccessTokenRequiredException)

Aggregations

AccessTokenRequiredException (org.springframework.security.oauth2.client.http.AccessTokenRequiredException)6 Test (org.junit.Test)3 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)3 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)3 IOException (java.io.IOException)2 URI (java.net.URI)2 HttpMethod (org.springframework.http.HttpMethod)2 ClientHttpRequest (org.springframework.http.client.ClientHttpRequest)2 ClientHttpRequestFactory (org.springframework.http.client.ClientHttpRequestFactory)2 OAuth2AccessDeniedException (org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException)2 OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)1 HttpMessageConversionException (org.springframework.http.converter.HttpMessageConversionException)1 AccessTokenRequest (org.springframework.security.oauth2.client.token.AccessTokenRequest)1 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)1 UserDeniedAuthorizationException (org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException)1