Search in sources :

Example 26 with InvalidTokenException

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

the class JwkVerifyingJwtAccessTokenConverter method decode.

/**
 * Decodes and validates the supplied JWT followed by signature verification
 * before returning the Claims from the JWT Payload.
 *
 * @param token the JSON Web Token
 * @return a <code>Map</code> of the JWT Claims
 * @throws JwkException if the JWT is invalid or if the JWS could not be verified
 */
@Override
protected Map<String, Object> decode(String token) {
    Map<String, String> headers = this.jwtHeaderConverter.convert(token);
    // Validate "kid" header
    String keyIdHeader = headers.get(KEY_ID);
    if (keyIdHeader == null) {
        throw new InvalidTokenException("Invalid JWT/JWS: " + KEY_ID + " is a required JOSE Header");
    }
    JwkDefinitionSource.JwkDefinitionHolder jwkDefinitionHolder = this.jwkDefinitionSource.getDefinitionLoadIfNecessary(keyIdHeader);
    if (jwkDefinitionHolder == null) {
        throw new InvalidTokenException("Invalid JOSE Header " + KEY_ID + " (" + keyIdHeader + ")");
    }
    JwkDefinition jwkDefinition = jwkDefinitionHolder.getJwkDefinition();
    // Validate "alg" header
    String algorithmHeader = headers.get(ALGORITHM);
    if (algorithmHeader == null) {
        throw new InvalidTokenException("Invalid JWT/JWS: " + ALGORITHM + " is a required JOSE Header");
    }
    if (jwkDefinition.getAlgorithm() != null && !algorithmHeader.equals(jwkDefinition.getAlgorithm().headerParamValue())) {
        throw new InvalidTokenException("Invalid JOSE Header " + ALGORITHM + " (" + algorithmHeader + ")" + " does not match algorithm associated to JWK with " + KEY_ID + " (" + keyIdHeader + ")");
    }
    // Verify signature
    SignatureVerifier verifier = jwkDefinitionHolder.getSignatureVerifier();
    Jwt jwt = JwtHelper.decode(token);
    jwt.verifySignature(verifier);
    Map<String, Object> claims = this.jsonParser.parseMap(jwt.getClaims());
    if (claims.containsKey(EXP) && claims.get(EXP) instanceof Integer) {
        Integer expiryInt = (Integer) claims.get(EXP);
        claims.put(EXP, new Long(expiryInt));
    }
    this.getJwtClaimsSetVerifier().verify(claims);
    return claims;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) Jwt(org.springframework.security.jwt.Jwt) SignatureVerifier(org.springframework.security.jwt.crypto.sign.SignatureVerifier)

Example 27 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 28 with InvalidTokenException

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 this.getStatusCode().value();
            }
        };
        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 29 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project cloudbreak by hortonworks.

the class CachedRemoteTokenServiceTest method testLoadAuthenticationWhenNoPublicKeyProvided.

@Test
public void testLoadAuthenticationWhenNoPublicKeyProvided() {
    when(identityClient.loadAuthentication(token, "clientSecret")).thenThrow(new InvalidTokenException("invalid_token"));
    CachedRemoteTokenService tokenService = new CachedRemoteTokenService("clientId", "clientSecret", "http://localhost:8089", null, identityClient);
    try {
        tokenService.loadAuthentication(token);
    } catch (InvalidTokenException e) {
        Assert.assertEquals("invalid_token", e.getMessage());
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) Test(org.junit.Test)

Example 30 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project cloudbreak by hortonworks.

the class IdentityClient method loadAuthentication.

// Based on this implementation org.springframework.security.oauth2.provider.token.RemoteTokenServices because we need specific headers
public Map<String, Object> loadAuthentication(String accessToken, String clientSecret) throws AuthenticationException, InvalidTokenException {
    MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
    String tokenName = "token";
    formData.add(tokenName, accessToken);
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
    headers.add("Authorization", "Basic " + Base64.encodeBase64String((clientId + ':' + clientSecret).getBytes()));
    Map<String, Object> response;
    try {
        response = checkTokenWebTarget.request().accept(MediaType.APPLICATION_FORM_URLENCODED_TYPE).headers(headers).post(Entity.form(formData), Map.class);
    } catch (BadRequestException ex) {
        LOGGER.warn(String.format("Token check failed for access token: '%s'.", accessToken), ex);
        throw new InvalidTokenException(accessToken);
    }
    if (response.containsKey("error")) {
        throw new InvalidTokenException(accessToken);
    }
    Assert.state(response.containsKey("client_id"), "Client id must be present in response from auth server");
    return response;
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) BadRequestException(javax.ws.rs.BadRequestException) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Aggregations

InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)33 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)11 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)8 Test (org.junit.Test)7 Date (java.util.Date)4 OrcidOauth2TokenDetail (org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail)4 DBUnitTest (org.orcid.test.DBUnitTest)4 IOException (java.io.IOException)3 Map (java.util.Map)3 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)3 Authentication (org.springframework.security.core.Authentication)3 Jwt (org.springframework.security.jwt.Jwt)3 OAuth2AccessDeniedException (org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException)3 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)3 OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)3 PublicKey (java.security.PublicKey)2 HashSet (java.util.HashSet)2 Supplier (java.util.function.Supplier)2 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)2 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)2