Search in sources :

Example 11 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException 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 12 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException 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)

Example 13 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project spring-security-oauth by spring-projects.

the class CheckTokenEndpoint method handleException.

@ExceptionHandler(InvalidTokenException.class)
public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
    logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
    // This isn't an oauth resource, so we don't want to send an
    // unauthorized code here. The client has already authenticated
    // successfully with basic auth and should just
    // get back the invalid token error.
    @SuppressWarnings("serial") InvalidTokenException e400 = new InvalidTokenException(e.getMessage()) {

        @Override
        public int getHttpErrorCode() {
            return 400;
        }
    };
    return exceptionTranslator.translate(e400);
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler)

Example 14 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationManager method authenticate.

/**
	 * Expects the incoming authentication request to have a principal value that is an access token value (e.g. from an
	 * authorization header). Loads an authentication from the {@link ResourceServerTokenServices} and checks that the
	 * resource id is contained in the {@link AuthorizationRequest} (if one is specified). Also copies authentication
	 * details over from the input to the output (e.g. typically so that the access token value and request details can
	 * be reported later).
	 * 
	 * @param authentication an authentication request containing an access token value as the principal
	 * @return an {@link OAuth2Authentication}
	 * 
	 * @see org.springframework.security.authentication.AuthenticationManager#authenticate(org.springframework.security.core.Authentication)
	 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        throw new InvalidTokenException("Invalid token (token not found)");
    }
    String token = (String) authentication.getPrincipal();
    OAuth2Authentication auth = tokenServices.loadAuthentication(token);
    if (auth == null) {
        throw new InvalidTokenException("Invalid token: " + token);
    }
    Collection<String> resourceIds = auth.getOAuth2Request().getResourceIds();
    if (resourceId != null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(resourceId)) {
        throw new OAuth2AccessDeniedException("Invalid token does not contain resource id (" + resourceId + ")");
    }
    checkClientDetails(auth);
    if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        // Guard against a cached copy of the same details
        if (!details.equals(auth.getDetails())) {
            // Preserve the authentication details from the one loaded by token services
            details.setDecodedDetails(auth.getDetails());
        }
    }
    auth.setDetails(authentication.getDetails());
    auth.setAuthenticated(true);
    return auth;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 15 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project spring-security-oauth by spring-projects.

the class RemoteTokenServices method loadAuthentication.

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add(tokenName, accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);
    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }
    Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
    return tokenConverter.extractAuthentication(map);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Aggregations

InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)21 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)8 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)6 Date (java.util.Date)4 Test (org.junit.Test)4 OrcidOauth2TokenDetail (org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail)4 DBUnitTest (org.orcid.test.DBUnitTest)4 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)4 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)3 OAuth2AccessDeniedException (org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException)3 InvalidScopeException (org.springframework.security.oauth2.common.exceptions.InvalidScopeException)3 OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)3 HashSet (java.util.HashSet)2 NoResultException (javax.persistence.NoResultException)2 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)2 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)2 Authentication (org.springframework.security.core.Authentication)2 Jwt (org.springframework.security.jwt.Jwt)2 JsonParser (com.fasterxml.jackson.core.JsonParser)1 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)1