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);
}
}
}
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;
}
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);
}
}
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;
}
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);
}
Aggregations