Search in sources :

Example 46 with Algorithm

use of com.auth0.jwt.Algorithm in project AuthGuard by AuthGuard.

the class JwtSignatureAlgorithmsTest method generateToken.

private String generateToken(final JwtConfig config) {
    final Algorithm algorithm = JwtConfigParser.parseAlgorithm(config.getAlgorithm(), config.getPublicKey(), config.getPrivateKey());
    final JwtGenerator jwtGenerator = new JwtGenerator(config);
    final AccountBO account = AccountBO.builder().id("id").build();
    final JWTCreator.Builder tokenBuilder = jwtGenerator.generateUnsignedToken(account, Duration.ofMinutes(5));
    return tokenBuilder.sign(algorithm);
}
Also used : AccountBO(com.nexblocks.authguard.service.model.AccountBO) JWTCreator(com.auth0.jwt.JWTCreator) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Example 47 with Algorithm

use of com.auth0.jwt.Algorithm in project AuthGuard by AuthGuard.

the class JwtTokenVerifierTest method newVerifierInstance.

private JwtTokenVerifier newVerifierInstance(final StrategyConfig strategyConfig) {
    jtiProvider = Mockito.mock(JtiProvider.class);
    final JwtConfig jwtConfig = jwtConfig();
    final Algorithm algorithm = JwtConfigParser.parseAlgorithm(jwtConfig.getAlgorithm(), jwtConfig.getPublicKey(), jwtConfig.getPrivateKey());
    return new JwtTokenVerifier(strategyConfig, jtiProvider, algorithm);
}
Also used : JwtConfig(com.nexblocks.authguard.service.config.JwtConfig) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Example 48 with Algorithm

use of com.auth0.jwt.Algorithm in project AuthGuard by AuthGuard.

the class JwtTokenVerifierTest method validateExpired.

@Test
void validateExpired() {
    final StrategyConfig strategyConfig = strategyConfig(false);
    final JwtConfig jwtConfig = jwtConfig();
    final AccountBO account = RANDOM.nextObject(AccountBO.class);
    final Algorithm algorithm = JwtConfigParser.parseAlgorithm(jwtConfig.getAlgorithm(), jwtConfig.getPublicKey(), jwtConfig.getPrivateKey());
    final JwtGenerator jwtGenerator = new JwtGenerator(jwtConfig);
    final String token = jwtGenerator.generateUnsignedToken(account, Duration.ofMinutes(5)).withExpiresAt(Date.from(Instant.now().minusSeconds(60))).sign(algorithm);
    final JwtTokenVerifier jwtTokenVerifier = newVerifierInstance(strategyConfig);
    final Either<Exception, DecodedJWT> validatedToken = jwtTokenVerifier.verify(token);
    assertThat(validatedToken.isLeft()).isTrue();
    assertThat(validatedToken.getLeft()).isInstanceOf(ServiceAuthorizationException.class);
}
Also used : AccountBO(com.nexblocks.authguard.service.model.AccountBO) JwtConfig(com.nexblocks.authguard.service.config.JwtConfig) StrategyConfig(com.nexblocks.authguard.service.config.StrategyConfig) Algorithm(com.auth0.jwt.algorithms.Algorithm) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) Test(org.junit.jupiter.api.Test)

Example 49 with Algorithm

use of com.auth0.jwt.Algorithm in project AuthGuard by AuthGuard.

the class JwtConfigParserTest method parseRsa512.

@Test
void parseRsa512() {
    final String publicKeyPath = "src/test/resources/rsa512-public.pem";
    final String privateKeyPath = "src/test/resources/rsa512-private.pem";
    final Algorithm algorithm = JwtConfigParser.parseAlgorithm("RSA512", publicKeyPath, privateKeyPath);
    final String jwt = JWT.create().withClaim("claim", "value").sign(algorithm);
    algorithm.verify(JWT.decode(jwt));
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) Test(org.junit.jupiter.api.Test)

Example 50 with Algorithm

use of com.auth0.jwt.Algorithm in project auth0-java-mvc-common by auth0.

the class IdTokenVerifier method verify.

/**
 * Verifies a provided ID Token follows the OIDC specification.
 * See https://openid.net/specs/openid-connect-core-1_0-final.html#IDTokenValidation
 *
 * @param token         the ID Token to verify.
 * @param verifyOptions the verification options, like audience, issuer, algorithm.
 * @throws TokenValidationException If the ID Token is null, its signing algorithm not supported, its signature invalid or one of its claim invalid.
 */
void verify(String token, Options verifyOptions) throws TokenValidationException {
    Validate.notNull(verifyOptions);
    if (isEmpty(token)) {
        throw new TokenValidationException("ID token is required but missing");
    }
    DecodedJWT decoded = verifyOptions.verifier.verifySignature(token);
    if (isEmpty(decoded.getIssuer())) {
        throw new TokenValidationException("Issuer (iss) claim must be a string present in the ID token");
    }
    if (!decoded.getIssuer().equals(verifyOptions.issuer)) {
        throw new TokenValidationException(String.format("Issuer (iss) claim mismatch in the ID token, expected \"%s\", found \"%s\"", verifyOptions.issuer, decoded.getIssuer()));
    }
    if (isEmpty(decoded.getSubject())) {
        throw new TokenValidationException("Subject (sub) claim must be a string present in the ID token");
    }
    final List<String> audience = decoded.getAudience();
    if (audience == null) {
        throw new TokenValidationException("Audience (aud) claim must be a string or array of strings present in the ID token");
    }
    if (!audience.contains(verifyOptions.audience)) {
        throw new TokenValidationException(String.format("Audience (aud) claim mismatch in the ID token; expected \"%s\" but found \"%s\"", verifyOptions.audience, decoded.getAudience()));
    }
    // validate org if set
    if (verifyOptions.organization != null) {
        String orgIdClaim = decoded.getClaim("org_id").asString();
        if (isEmpty(orgIdClaim)) {
            throw new TokenValidationException("Organization Id (org_id) claim must be a string present in the ID token");
        }
        if (!verifyOptions.organization.equals(orgIdClaim)) {
            throw new TokenValidationException(String.format("Organization (org_id) claim mismatch in the ID token; expected \"%s\" but found \"%s\"", verifyOptions.organization, orgIdClaim));
        }
    }
    final Calendar cal = Calendar.getInstance();
    final Date now = verifyOptions.clock != null ? verifyOptions.clock : cal.getTime();
    final int clockSkew = verifyOptions.clockSkew != null ? verifyOptions.clockSkew : DEFAULT_CLOCK_SKEW;
    if (decoded.getExpiresAt() == null) {
        throw new TokenValidationException("Expiration Time (exp) claim must be a number present in the ID token");
    }
    cal.setTime(decoded.getExpiresAt());
    cal.add(Calendar.SECOND, clockSkew);
    Date expDate = cal.getTime();
    if (now.after(expDate)) {
        throw new TokenValidationException(String.format("Expiration Time (exp) claim error in the ID token; current time (%d) is after expiration time (%d)", now.getTime() / 1000, expDate.getTime() / 1000));
    }
    if (decoded.getIssuedAt() == null) {
        throw new TokenValidationException("Issued At (iat) claim must be a number present in the ID token");
    }
    cal.setTime(decoded.getIssuedAt());
    cal.add(Calendar.SECOND, -1 * clockSkew);
    if (verifyOptions.nonce != null) {
        String nonceClaim = decoded.getClaim(NONCE_CLAIM).asString();
        if (isEmpty(nonceClaim)) {
            throw new TokenValidationException("Nonce (nonce) claim must be a string present in the ID token");
        }
        if (!verifyOptions.nonce.equals(nonceClaim)) {
            throw new TokenValidationException(String.format("Nonce (nonce) claim mismatch in the ID token; expected \"%s\", found \"%s\"", verifyOptions.nonce, nonceClaim));
        }
    }
    if (audience.size() > 1) {
        String azpClaim = decoded.getClaim(AZP_CLAIM).asString();
        if (isEmpty(azpClaim)) {
            throw new TokenValidationException("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");
        }
        if (!verifyOptions.audience.equals(azpClaim)) {
            throw new TokenValidationException(String.format("Authorized Party (azp) claim mismatch in the ID token; expected \"%s\", found \"%s\"", verifyOptions.audience, azpClaim));
        }
    }
    if (verifyOptions.maxAge != null) {
        Date authTime = decoded.getClaim(AUTH_TIME_CLAIM).asDate();
        if (authTime == null) {
            throw new TokenValidationException("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");
        }
        cal.setTime(authTime);
        cal.add(Calendar.SECOND, verifyOptions.maxAge);
        cal.add(Calendar.SECOND, clockSkew);
        Date authTimeDate = cal.getTime();
        if (now.after(authTimeDate)) {
            throw new TokenValidationException(String.format("Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (%d) is after last auth at (%d)", now.getTime() / 1000, authTimeDate.getTime() / 1000));
        }
    }
}
Also used : Calendar(java.util.Calendar) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)206 Test (org.junit.Test)160 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)90 JWTVerifier (com.auth0.jwt.JWTVerifier)79 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)79 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)61 Date (java.util.Date)57 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)51 RSAPublicKey (java.security.interfaces.RSAPublicKey)36 ECPublicKey (java.security.interfaces.ECPublicKey)34 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)31 IOException (java.io.IOException)30 JWTCreator (com.auth0.jwt.JWTCreator)28 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)25 ECPrivateKey (java.security.interfaces.ECPrivateKey)23 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 HashMap (java.util.HashMap)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 JsonObject (com.google.gson.JsonObject)15