Search in sources :

Example 16 with InvalidTokenException

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

the class JwtAccessTokenConverter method decode.

protected Map<String, Object> decode(String token) {
    try {
        Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
        String content = jwt.getClaims();
        Map<String, Object> map = objectMapper.parseMap(content);
        if (map.containsKey(EXP) && map.get(EXP) instanceof Integer) {
            Integer intValue = (Integer) map.get(EXP);
            map.put(EXP, new Long(intValue));
        }
        return map;
    } catch (Exception e) {
        throw new InvalidTokenException("Cannot convert access token to JSON", e);
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) Jwt(org.springframework.security.jwt.Jwt) InvalidSignatureException(org.springframework.security.jwt.crypto.sign.InvalidSignatureException) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException)

Example 17 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");
    }
    JwkDefinition jwkDefinition = this.jwkDefinitionSource.getDefinitionLoadIfNecessary(keyIdHeader);
    if (jwkDefinition == null) {
        throw new InvalidTokenException("Invalid JOSE Header " + KEY_ID + " (" + keyIdHeader + ")");
    }
    // Validate "alg" header
    String algorithmHeader = headers.get(ALGORITHM);
    if (algorithmHeader == null) {
        throw new InvalidTokenException("Invalid JWT/JWS: " + ALGORITHM + " is a required JOSE Header");
    }
    if (!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 = this.jwkDefinitionSource.getVerifier(keyIdHeader);
    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));
    }
    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 18 with InvalidTokenException

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

the class JwtHeaderConverter method convert.

/**
	 * Converts the supplied JSON Web Token to a <code>Map</code> of JWT Header Parameters.
	 *
	 * @param token the JSON Web Token
	 * @return a <code>Map</code> of JWT Header Parameters
	 * @throws JwkException if the JWT is invalid
	 */
@Override
public Map<String, String> convert(String token) {
    Map<String, String> headers;
    int headerEndIndex = token.indexOf('.');
    if (headerEndIndex == -1) {
        throw new InvalidTokenException("Invalid JWT. Missing JOSE Header.");
    }
    byte[] decodedHeader = Codecs.b64UrlDecode(token.substring(0, headerEndIndex));
    JsonParser parser = null;
    try {
        parser = this.factory.createParser(decodedHeader);
        headers = new HashMap<String, String>();
        if (parser.nextToken() == JsonToken.START_OBJECT) {
            while (parser.nextToken() == JsonToken.FIELD_NAME) {
                String headerName = parser.getCurrentName();
                parser.nextToken();
                String headerValue = parser.getValueAsString();
                headers.put(headerName, headerValue);
            }
        }
    } catch (IOException ex) {
        throw new InvalidTokenException("An I/O error occurred while reading the JWT: " + ex.getMessage(), ex);
    } finally {
        try {
            if (parser != null)
                parser.close();
        } catch (IOException ex) {
        }
    }
    return headers;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) IOException(java.io.IOException) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 19 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project ORCID-Source by ORCID.

the class OrcidRandomValueTokenServicesImpl method loadAuthentication.

@Override
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException {
    OAuth2AccessToken accessToken = orcidTokenStore.readAccessToken(accessTokenValue);
    if (accessToken == null) {
        throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
    } else {
        // If it is, respect the token expiration
        if (accessToken.isExpired()) {
            orcidTokenStore.removeAccessToken(accessToken);
            throw new InvalidTokenException("Access token expired: " + accessTokenValue);
        }
        Map<String, Object> additionalInfo = accessToken.getAdditionalInformation();
        if (additionalInfo != null) {
            String clientId = (String) additionalInfo.get(OrcidOauth2Constants.CLIENT_ID);
            ClientDetailsEntity clientEntity = clientDetailsEntityCacheManager.retrieve(clientId);
            try {
                orcidOAuth2RequestValidator.validateClientIsEnabled(clientEntity);
            } catch (LockedException le) {
                throw new InvalidTokenException(le.getMessage());
            }
        }
    }
    OAuth2Authentication result = orcidTokenStore.readAuthentication(accessToken);
    return result;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) LockedException(org.orcid.core.security.aop.LockedException) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication)

Example 20 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException in project ORCID-Source by ORCID.

the class OrcidRefreshTokenTokenGranterTest method tryToCreateRefreshTokenWithInvalidRefreshTokenTest.

@Test
public void tryToCreateRefreshTokenWithInvalidRefreshTokenTest() {
    // Create token, try to create refresh token with invalid refresh value,
    // fail
    long time = System.currentTimeMillis();
    String parentScope = "/person/update";
    String tokenValue = "parent-token-" + time;
    String refreshTokenValue = "refresh-token-" + time;
    Boolean revokeOld = true;
    Date parentTokenExpiration = new Date(time + 10000);
    Long expireIn = null;
    OrcidOauth2TokenDetail parent = createToken(CLIENT_ID_1, USER_ORCID, tokenValue, refreshTokenValue, parentTokenExpiration, parentScope);
    try {
        //Change the value we are going to use for the refresh token
        parent.setRefreshTokenValue("invalid-value");
        generateRefreshToken(parent, null, revokeOld, expireIn, parentScope);
        fail();
    } catch (InvalidTokenException e) {
        assertTrue(e.getMessage().contains("Token and refresh token does not match"));
    } catch (Exception e) {
        fail();
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) Date(java.util.Date) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) NoResultException(javax.persistence.NoResultException) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

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