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