use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project ORCID-Source by ORCID.
the class OrcidRandomValueTokenServicesTest method tokenExpiredDoesntWorkTest.
@Test
public void tokenExpiredDoesntWorkTest() {
OrcidOauth2TokenDetail expiredToken = new OrcidOauth2TokenDetail();
expiredToken.setApproved(true);
expiredToken.setAuthenticationKey("authentication-key");
expiredToken.setClientDetailsId("4444-4444-4444-4441");
expiredToken.setProfile(new ProfileEntity("4444-4444-4444-4442"));
expiredToken.setResourceId("orcid");
expiredToken.setScope("/read-limited");
expiredToken.setTokenExpiration(new Date(System.currentTimeMillis() - 1000));
expiredToken.setTokenValue("token-value");
orcidOauthTokenDetailService.removeConflictsAndCreateNew(expiredToken);
// The first time we try to use it, we get a InvalidTokenException with message Access token expired: token-value
try {
tokenServices.loadAuthentication("token-value");
fail();
} catch (InvalidTokenException e) {
assertEquals("Access token expired: token-value", e.getMessage());
}
// Second time we try to use it, we get a InvalidTokenException with message Invalid access token: token-value
try {
tokenServices.loadAuthentication("token-value");
fail();
} catch (InvalidTokenException e) {
assertEquals("Invalid access token: token-value", e.getMessage());
}
}
use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project ORCID-Source by ORCID.
the class OrcidTokenStoreServiceImpl method getOAuth2AuthenticationFromDetails.
private OAuth2Authentication getOAuth2AuthenticationFromDetails(OrcidOauth2TokenDetail details) {
if (details != null) {
ClientDetailsEntity clientDetailsEntity = clientDetailsEntityCacheManager.retrieve(details.getClientDetailsId());
Authentication authentication = null;
AuthorizationRequest request = null;
if (clientDetailsEntity != null) {
//Check member is not locked
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetailsEntity);
Set<String> scopes = OAuth2Utils.parseParameterList(details.getScope());
request = new AuthorizationRequest(clientDetailsEntity.getClientId(), scopes);
request.setAuthorities(clientDetailsEntity.getAuthorities());
Set<String> resourceIds = new HashSet<>();
resourceIds.add(details.getResourceId());
request.setResourceIds(resourceIds);
request.setApproved(details.isApproved());
ProfileEntity profile = details.getProfile();
if (profile != null) {
authentication = new OrcidOauth2UserAuthentication(profile, details.isApproved());
}
}
return new OrcidOAuth2Authentication(request, authentication, details.getTokenValue());
}
throw new InvalidTokenException("Token not found");
}
use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project ORCID-Source by ORCID.
the class OrcidClientCredentialEndPointDelegatorTest method generateRefreshTokenTest.
@Test
public void generateRefreshTokenTest() {
//Generate the access token
SecurityContextTestUtils.setUpSecurityContextForClientOnly(CLIENT_ID_1, ScopePathType.ACTIVITIES_UPDATE, ScopePathType.READ_LIMITED);
OrcidOauth2AuthoriziationCodeDetail authCode = createAuthorizationCode("code-1", CLIENT_ID_1, "http://www.APP-5555555555555555.com/redirect/oauth", true, "/activities/update");
MultivaluedMap<String, String> formParams = new MultivaluedMapImpl();
formParams.add("client_id", CLIENT_ID_1);
formParams.add("client_secret", "DhkFj5EI0qp6GsUKi55Vja+h+bsaKpBx");
formParams.add("grant_type", "authorization_code");
formParams.add("redirect_uri", "http://www.APP-5555555555555555.com/redirect/oauth");
formParams.add("code", authCode.getId());
Response response = orcidClientCredentialEndPointDelegator.obtainOauth2Token(null, formParams);
assertNotNull(response);
assertNotNull(response.getEntity());
DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) response.getEntity();
assertNotNull(token);
assertTrue(!PojoUtil.isEmpty(token.getValue()));
assertNotNull(token.getRefreshToken());
assertTrue(!PojoUtil.isEmpty(token.getRefreshToken().getValue()));
//Generate the refresh token
MultivaluedMap<String, String> refreshTokenformParams = new MultivaluedMapImpl();
refreshTokenformParams.add("client_id", CLIENT_ID_1);
refreshTokenformParams.add("client_secret", "DhkFj5EI0qp6GsUKi55Vja+h+bsaKpBx");
refreshTokenformParams.add("grant_type", "refresh_token");
refreshTokenformParams.add("redirect_uri", "http://www.APP-5555555555555555.com/redirect/oauth");
refreshTokenformParams.add("refresh_token", token.getRefreshToken().getValue());
String authorization = "bearer " + token.getValue();
Response refreshTokenResponse = orcidClientCredentialEndPointDelegator.obtainOauth2Token(authorization, refreshTokenformParams);
assertNotNull(refreshTokenResponse);
assertNotNull(refreshTokenResponse.getEntity());
DefaultOAuth2AccessToken refreshToken = (DefaultOAuth2AccessToken) refreshTokenResponse.getEntity();
assertNotNull(refreshToken);
assertTrue(!PojoUtil.isEmpty(refreshToken.getValue()));
assertNotNull(refreshToken.getRefreshToken());
assertTrue(!PojoUtil.isEmpty(refreshToken.getRefreshToken().getValue()));
//Assert that both tokens expires at the same time
assertEquals(token.getExpiration(), refreshToken.getExpiration());
//Try to generate another one, and fail, because parent token was disabled
try {
orcidClientCredentialEndPointDelegator.obtainOauth2Token(authorization, refreshTokenformParams);
} catch (InvalidTokenException e) {
assertTrue(e.getMessage().contains("Parent token is disabled"));
}
}
use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project spring-security-oauth by spring-projects.
the class OAuth2ClientAuthenticationProcessingFilter method attemptAuthentication.
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
OAuth2AccessToken accessToken;
try {
accessToken = restTemplate.getAccessToken();
} catch (OAuth2Exception e) {
BadCredentialsException bad = new BadCredentialsException("Could not obtain access token", e);
publish(new OAuth2AuthenticationFailureEvent(bad));
throw bad;
}
try {
OAuth2Authentication result = tokenServices.loadAuthentication(accessToken.getValue());
if (authenticationDetailsSource != null) {
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, accessToken.getValue());
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, accessToken.getTokenType());
result.setDetails(authenticationDetailsSource.buildDetails(request));
}
publish(new AuthenticationSuccessEvent(result));
return result;
} catch (InvalidTokenException e) {
BadCredentialsException bad = new BadCredentialsException("Could not obtain user details from token", e);
publish(new OAuth2AuthenticationFailureEvent(bad));
throw bad;
}
}
use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException 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);
}
}
}
Aggregations