Search in sources :

Example 36 with Verification

use of com.auth0.jwt.interfaces.Verification in project opencast by opencast.

the class JWTVerifier method verify.

/**
 * Verifies a given decoded JWT with the given claim constraints and algorithms. The verification has to be
 * successful with at least one provided algorithm. Otherwise a {@link JWTVerificationException} is thrown.
 *
 * @param jwt The decoded JWT.
 * @param claimConstraints The claim constraints.
 * @param algorithms The algorithms.
 * @return The decoded and verified JWT.
 * @throws JWTVerificationException If the JWT cannot be verified successfully.
 */
public static DecodedJWT verify(DecodedJWT jwt, List<String> claimConstraints, Algorithm... algorithms) throws JWTVerificationException {
    Assert.notNull(jwt, "A decoded JWT must be set");
    Assert.notEmpty(claimConstraints, "Claim constraints must be set");
    Assert.notEmpty(algorithms, "Algorithms must be set");
    Assert.isTrue(algorithmsMatch(algorithms), "Algorithms must be of same class");
    boolean verified = false;
    Exception lastException = new JWTVerificationException("JWT could not be verified");
    for (Algorithm algorithm : algorithms) {
        try {
            // General verification
            JWT.require(algorithm).build().verify(jwt);
            // Claim constraints verification
            ExpressionParser parser = new SpelExpressionParser();
            for (String constraint : claimConstraints) {
                Expression exp = parser.parseExpression(constraint);
                if (!exp.getValue(jwt.getClaims(), Boolean.class)) {
                    throw new JWTVerificationException("The claims did not fulfill constraint '" + constraint + "'");
                }
            }
            // Verification was successful if no exception has been thrown
            verified = true;
            break;
        } catch (JWTVerificationException | EvaluationException | ParseException e) {
            // Ignore for now and try next algorithm
            lastException = e;
        }
    }
    // If verification was not successful until here, throw last known exception
    if (!verified) {
        throw new JWTVerificationException(lastException.getMessage());
    }
    return jwt;
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) Expression(org.springframework.expression.Expression) ExpressionParser(org.springframework.expression.ExpressionParser) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) EvaluationException(org.springframework.expression.EvaluationException) ParseException(org.springframework.expression.ParseException) Algorithm(com.auth0.jwt.algorithms.Algorithm) JwkException(com.auth0.jwk.JwkException) EvaluationException(org.springframework.expression.EvaluationException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ParseException(org.springframework.expression.ParseException)

Example 37 with Verification

use of com.auth0.jwt.interfaces.Verification in project fizz-gateway-community by wehotel.

the class JwtAuthPluginFilter method verify.

/**
 * Verify JWT
 *
 * @param token
 * @param secretKey key for HS256/HS384/HS512
 * @param publicKey pub key for RSA or ECDSA
 * @return
 * @throws Exception
 */
public DecodedJWT verify(String token, String secretKey, String publicKey) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        String alg = jwt.getAlgorithm();
        Algorithm algorithm = null;
        switch(alg) {
            case "HS256":
                algorithm = Algorithm.HMAC256(secretKey);
                break;
            case "HS384":
                algorithm = Algorithm.HMAC384(secretKey);
                break;
            case "HS512":
                algorithm = Algorithm.HMAC512(secretKey);
                break;
            case "RS256":
                algorithm = Algorithm.RSA256((RSAPublicKey) PemUtils.readPublicKeyFromString(publicKey, RSA), null);
                break;
            case "RS384":
                algorithm = Algorithm.RSA384((RSAPublicKey) PemUtils.readPublicKeyFromString(publicKey, RSA), null);
                break;
            case "RS512":
                algorithm = Algorithm.RSA512((RSAPublicKey) PemUtils.readPublicKeyFromString(publicKey, RSA), null);
                break;
            case "ES256":
                algorithm = Algorithm.ECDSA256((ECPublicKey) PemUtils.readPublicKeyFromString(publicKey, EC), null);
                break;
            case "ES256K":
                algorithm = Algorithm.ECDSA256K((ECPublicKey) PemUtils.readPublicKeyFromString(publicKey, EC), null);
                break;
            case "ES384":
                algorithm = Algorithm.ECDSA384((ECPublicKey) PemUtils.readPublicKeyFromString(publicKey, EC), null);
                break;
            case "ES512":
                algorithm = Algorithm.ECDSA512((ECPublicKey) PemUtils.readPublicKeyFromString(publicKey, EC), null);
                break;
        }
        if (algorithm == null) {
            // Algorithm NOT Supported
            log.warn("{} Algorithm NOT Supported", alg);
        } else {
            JWTVerifier verifier = JWT.require(algorithm).build();
            try {
                return verifier.verify(token);
            } catch (JWTVerificationException e) {
                // Verification failed
                log.warn("JWT verification failed: {}", e.getMessage());
            }
        }
    } catch (Exception e) {
        log.warn("JWT verification exception", e);
    }
    return null;
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException)

Example 38 with Verification

use of com.auth0.jwt.interfaces.Verification in project sda-dropwizard-commons by SDA-SE.

the class AuthRSA256Service method auth.

@Override
public Map<String, Claim> auth(String authorizationToken) {
    try {
        String keyId = JWT.decode(authorizationToken).getKeyId();
        if (keyId == null) {
            // check all keys without id
            List<LoadedPublicKey> keysWithoutId = rsaPublicKeyLoader.getKeysWithoutId();
            if (keysWithoutId.size() > 1) {
                LOG.warn("Verifying token without kid trying {} public keys", keysWithoutId.size());
            }
            Collections.reverse(keysWithoutId);
            return keysWithoutId.stream().map(k -> verifyJwtSignature(authorizationToken, k)).filter(Optional::isPresent).map(Optional::get).findFirst().orElseThrow(() -> new JwtAuthException("Could not verify JWT without kid.")).getClaims();
        } else {
            LoadedPublicKey loadedPublicKey = rsaPublicKeyLoader.getLoadedPublicKey(keyId);
            if (loadedPublicKey == null) {
                LOG.error("No key found for verification, matching the requested kid {}", keyId);
                throw new JwtAuthException("Could not verify JWT with the requested kid.");
            }
            DecodedJWT jwt = verifyJwtSignature(authorizationToken, loadedPublicKey).orElseThrow(() -> new JwtAuthException("Verifying token failed"));
            return jwt.getClaims();
        }
    } catch (JWTVerificationException e) {
        throw new JwtAuthException(e);
    }
}
Also used : JWT(com.auth0.jwt.JWT) Logger(org.slf4j.Logger) Verification(com.auth0.jwt.interfaces.Verification) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) LoadedPublicKey(org.sdase.commons.server.auth.key.LoadedPublicKey) LoggerFactory(org.slf4j.LoggerFactory) JwtAuthException(org.sdase.commons.server.auth.error.JwtAuthException) RsaPublicKeyLoader(org.sdase.commons.server.auth.key.RsaPublicKeyLoader) StringUtils(org.apache.commons.lang3.StringUtils) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) Algorithm(com.auth0.jwt.algorithms.Algorithm) List(java.util.List) Validate(org.apache.commons.lang3.Validate) Map(java.util.Map) Optional(java.util.Optional) Claim(com.auth0.jwt.interfaces.Claim) Collections(java.util.Collections) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) LoadedPublicKey(org.sdase.commons.server.auth.key.LoadedPublicKey) Optional(java.util.Optional) JwtAuthException(org.sdase.commons.server.auth.error.JwtAuthException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 39 with Verification

use of com.auth0.jwt.interfaces.Verification in project sda-dropwizard-commons by SDA-SE.

the class AuthRSA256Service method verifyJwtSignature.

private Optional<DecodedJWT> verifyJwtSignature(String authorizationToken, LoadedPublicKey loadedPublicKey) {
    try {
        Verification jwtVerification = JWT.require(Algorithm.RSA256(loadedPublicKey.getPublicKey(), null)).acceptLeeway(leeway);
        if (StringUtils.isNotBlank(loadedPublicKey.getRequiredIssuer())) {
            jwtVerification = jwtVerification.withIssuer(loadedPublicKey.getRequiredIssuer());
        }
        DecodedJWT jwt = jwtVerification.build().verify(authorizationToken);
        return Optional.of(jwt);
    } catch (TokenExpiredException e) {
        LOG.warn("Verifying token failed.", e);
        return Optional.empty();
    } catch (JWTVerificationException e) {
        LOG.error("Verifying token failed.", e);
        return Optional.empty();
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) Verification(com.auth0.jwt.interfaces.Verification) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 40 with Verification

use of com.auth0.jwt.interfaces.Verification in project auth0-java by auth0.

the class JobsEntityTest method shouldSendUserVerificationEmailWithIdentity.

@Test
public void shouldSendUserVerificationEmailWithIdentity() throws Exception {
    EmailVerificationIdentity identity = new EmailVerificationIdentity("google-oauth2", "1234");
    Request<Job> request = api.jobs().sendVerificationEmail("google-oauth2|1234", "AaiyAPdpYdesoKnqjj8HJqRn4T5titww", identity);
    assertThat(request, is(notNullValue()));
    server.jsonResponse(MGMT_JOB_POST_VERIFICATION_EMAIL, 200);
    Job response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();
    assertThat(recordedRequest, hasMethodAndPath("POST", "/api/v2/jobs/verification-email"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    Map<String, Object> body = bodyFromRequest(recordedRequest);
    assertThat(body.size(), is(3));
    assertThat(body, hasEntry("user_id", "google-oauth2|1234"));
    assertThat(body, hasEntry("client_id", "AaiyAPdpYdesoKnqjj8HJqRn4T5titww"));
    Map<String, String> identityMap = new HashMap<>();
    identityMap.put("provider", "google-oauth2");
    identityMap.put("user_id", "1234");
    assertThat(body, hasEntry("identity", identityMap));
    assertThat(response, is(notNullValue()));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HashMap(java.util.HashMap) Job(com.auth0.json.mgmt.jobs.Job) EmailVerificationIdentity(com.auth0.json.mgmt.EmailVerificationIdentity) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)29 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)28 Algorithm (com.auth0.jwt.algorithms.Algorithm)14 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)11 Date (java.util.Date)11 Verification (com.auth0.jwt.interfaces.Verification)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 JWTVerifier (com.auth0.jwt.JWTVerifier)5 RSAPublicKey (java.security.interfaces.RSAPublicKey)5 Job (com.auth0.json.mgmt.jobs.Job)4 Claim (com.auth0.jwt.interfaces.Claim)4 Clock (com.auth0.jwt.interfaces.Clock)4 List (java.util.List)4 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)4 JWT (com.auth0.jwt.JWT)3 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 IOException (java.io.IOException)3 ByteBuffer (java.nio.ByteBuffer)3 FloodlightModuleException (net.floodlightcontroller.core.module.FloodlightModuleException)3