Search in sources :

Example 36 with ClientHttpResponse

use of org.springframework.http.client.ClientHttpResponse 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 37 with ClientHttpResponse

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

the class OAuth2ContextSetup method createRestTemplate.

private OAuth2RestTemplate createRestTemplate(OAuth2ProtectedResourceDetails resource, AccessTokenRequest request) {
    OAuth2ClientContext context = new DefaultOAuth2ClientContext(request);
    OAuth2RestTemplate client = new OAuth2RestTemplate(resource, context);
    setupConnectionFactory(client);
    client.setErrorHandler(new DefaultResponseErrorHandler() {

        // Pass errors through in response entity for status code analysis
        public boolean hasError(ClientHttpResponse response) throws IOException {
            return false;
        }
    });
    if (accessTokenProvider != null) {
        client.setAccessTokenProvider(accessTokenProvider);
    }
    return client;
}
Also used : DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) DefaultOAuth2ClientContext(org.springframework.security.oauth2.client.DefaultOAuth2ClientContext) DefaultOAuth2ClientContext(org.springframework.security.oauth2.client.DefaultOAuth2ClientContext) OAuth2ClientContext(org.springframework.security.oauth2.client.OAuth2ClientContext) IOException(java.io.IOException) OAuth2RestTemplate(org.springframework.security.oauth2.client.OAuth2RestTemplate) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Example 38 with ClientHttpResponse

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

the class OAuth2AccessTokenSupport method retrieveToken.

protected OAuth2AccessToken retrieveToken(AccessTokenRequest request, OAuth2ProtectedResourceDetails resource, MultiValueMap<String, String> form, HttpHeaders headers) throws OAuth2AccessDeniedException {
    try {
        // Prepare headers and form before going into rest template call in case the URI is affected by the result
        authenticationHandler.authenticateTokenRequest(resource, form, headers);
        // Opportunity to customize form and headers
        tokenRequestEnhancer.enhance(request, resource, form, headers);
        final AccessTokenRequest copy = request;
        final ResponseExtractor<OAuth2AccessToken> delegate = getResponseExtractor();
        ResponseExtractor<OAuth2AccessToken> extractor = new ResponseExtractor<OAuth2AccessToken>() {

            @Override
            public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {
                if (response.getHeaders().containsKey("Set-Cookie")) {
                    copy.setCookie(response.getHeaders().getFirst("Set-Cookie"));
                }
                return delegate.extractData(response);
            }
        };
        return getRestTemplate().execute(getAccessTokenUri(resource, form), getHttpMethod(), getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());
    } catch (OAuth2Exception oe) {
        throw new OAuth2AccessDeniedException("Access token denied.", resource, oe);
    } catch (RestClientException rce) {
        throw new OAuth2AccessDeniedException("Error requesting access token.", resource, rce);
    }
}
Also used : OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) RestClientException(org.springframework.web.client.RestClientException) ResponseExtractor(org.springframework.web.client.ResponseExtractor) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 39 with ClientHttpResponse

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

the class AuthorizationCodeAccessTokenProvider method obtainAuthorizationCode.

public String obtainAuthorizationCode(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details;
    HttpHeaders headers = getHeadersForAuthorizationRequest(request);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) {
        form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        for (String scope : details.getScope()) {
            form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        }
    } else {
        form.putAll(getParametersForAuthorizeRequest(resource, request));
    }
    authorizationRequestEnhancer.enhance(request, resource, form, headers);
    final AccessTokenRequest copy = request;
    final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor();
    ResponseExtractor<ResponseEntity<Void>> extractor = new ResponseExtractor<ResponseEntity<Void>>() {

        @Override
        public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
            if (response.getHeaders().containsKey("Set-Cookie")) {
                copy.setCookie(response.getHeaders().getFirst("Set-Cookie"));
            }
            return delegate.extractData(response);
        }
    };
    // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by
    // subclasses
    ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(), HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());
    if (response.getStatusCode() == HttpStatus.OK) {
        // Need to re-submit with approval...
        throw getUserApprovalSignal(resource, request);
    }
    URI location = response.getHeaders().getLocation();
    String query = location.getQuery();
    Map<String, String> map = OAuth2Utils.extractMap(query);
    if (map.containsKey("state")) {
        request.setStateKey(map.get("state"));
        if (request.getPreservedState() == null) {
            String redirectUri = resource.getRedirectUri(request);
            if (redirectUri != null) {
                request.setPreservedState(redirectUri);
            } else {
                request.setPreservedState(new Object());
            }
        }
    }
    String code = map.get("code");
    if (code == null) {
        throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap());
    }
    request.set("code", code);
    return code;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ResponseExtractor(org.springframework.web.client.ResponseExtractor) URI(java.net.URI) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) ResponseEntity(org.springframework.http.ResponseEntity) AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Example 40 with ClientHttpResponse

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

the class OAuth2RestTemplateTests method open.

@Before
public void open() throws Exception {
    resource = new BaseOAuth2ProtectedResourceDetails();
    // Facebook and older specs:
    resource.setTokenName("bearer_token");
    restTemplate = new OAuth2RestTemplate(resource);
    restTemplate.setAccessTokenProvider(accessTokenProvider);
    request = Mockito.mock(ClientHttpRequest.class);
    headers = new HttpHeaders();
    Mockito.when(request.getHeaders()).thenReturn(headers);
    ClientHttpResponse response = Mockito.mock(ClientHttpResponse.class);
    HttpStatus statusCode = HttpStatus.OK;
    Mockito.when(response.getStatusCode()).thenReturn(statusCode);
    Mockito.when(request.execute()).thenReturn(response);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpStatus(org.springframework.http.HttpStatus) BaseOAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) Before(org.junit.Before)

Aggregations

ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)71 Test (org.junit.Test)35 IOException (java.io.IOException)25 ResponseErrorHandler (org.springframework.web.client.ResponseErrorHandler)21 HttpHeaders (org.springframework.http.HttpHeaders)18 URI (java.net.URI)17 DefaultResponseErrorHandler (org.springframework.web.client.DefaultResponseErrorHandler)15 ClientHttpRequest (org.springframework.http.client.ClientHttpRequest)14 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)11 RestTemplate (org.springframework.web.client.RestTemplate)11 ResponseExtractor (org.springframework.web.client.ResponseExtractor)10 ByteArrayInputStream (java.io.ByteArrayInputStream)8 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7 ServiceError (com.kixeye.chassis.transport.dto.ServiceError)6 SerDeHttpMessageConverter (com.kixeye.chassis.transport.http.SerDeHttpMessageConverter)6 MessageSerDe (com.kixeye.chassis.transport.serde.MessageSerDe)6 JsonJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe)6 ProtobufMessageSerDe (com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe)6 XmlMessageSerDe (com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe)6 YamlJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe)6