Search in sources :

Example 66 with Algorithm

use of com.auth0.jwt.Algorithm in project stream-java by GetStream.

the class Auth method buildBackendToken.

public static Token buildBackendToken(String secret, TokenResource resource, TokenAction action, String feedID, String userID) {
    final Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTCreator.Builder builder = JWT.create();
    builder.withClaim("resource", resource.toString());
    builder.withClaim("action", action.toString());
    builder.withClaim("feed_id", feedID);
    if (userID != null) {
        builder.withClaim("user_id", userID);
    }
    return new Token(builder.sign(algorithm));
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Token(io.getstream.core.http.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Example 67 with Algorithm

use of com.auth0.jwt.Algorithm in project DJI-Cloud-API-Demo by dji-sdk.

the class JwtUtil method createToken.

/**
 * Create a token based on custom information.
 * @param claims custom information
 * @return token
 */
public static String createToken(Map<String, String> claims) {
    Date now = new Date();
    JWTCreator.Builder builder = JWT.create();
    // Add custom information to the token's payload segment.
    claims.forEach(builder::withClaim);
    String token = builder.withIssuer(issuer).withSubject(subject).withIssuedAt(now).withExpiresAt(new Date(now.getTime() + age)).withNotBefore(now).sign(algorithm);
    log.debug("token created. " + token);
    return token;
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Date(java.util.Date)

Example 68 with Algorithm

use of com.auth0.jwt.Algorithm in project simple-jwt by vorbote.

the class AccessKeyUtil method Info.

/**
 * Decode the token, and you can easily get some info from
 * this token.
 *
 * @param token The token.
 * @return The decoded jwt token.
 * @throws com.auth0.jwt.exceptions.AlgorithmMismatchException     If the algorithm stated in the token's
 *                                                                 header it's not equal to the one
 *                                                                 defined in the JWTVerifier.
 * @throws com.auth0.jwt.exceptions.SignatureVerificationException If the signature is invalid.
 * @throws com.auth0.jwt.exceptions.TokenExpiredException          If the token has expired.
 * @throws com.auth0.jwt.exceptions.InvalidClaimException          If a claim contained a different value
 *                                                                 than the expected one.
 * @throws com.auth0.jwt.exceptions.JWTVerificationException       If any of the verification steps fail
 * @see JWTVerifier#verify(String)
 */
public DecodedJWT Info(String token) {
    JWTVerifier verifier;
    switch(algorithm) {
        case HS256:
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            break;
        case HS384:
            verifier = JWT.require(Algorithm.HMAC384(secret)).build();
            break;
        case HS512:
            verifier = JWT.require(Algorithm.HMAC512(secret)).build();
            break;
        default:
            // 这里理论上应该抛出异常的,但是实在是懒得做了,就先这样吧。
            // 至于其他的算法,后续再考虑加上。
            verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            log.error("This algorithm is not supported yet, will use HMAC256 by default.");
    }
    return verifier.verify(token);
}
Also used : JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 69 with Algorithm

use of com.auth0.jwt.Algorithm in project bank-of-anthos by GoogleCloudPlatform.

the class JWTVerifierGenerator method generateJWTVerifier.

@Bean(name = "verifier")
public JWTVerifier generateJWTVerifier(@Value("${PUB_KEY_PATH}") final String publicKeyPath) {
    // load public key from file
    try {
        LOGGER.debug("Generating JWT token verifier");
        String keyStr = new String(Files.readAllBytes(Paths.get(publicKeyPath)));
        keyStr = keyStr.replaceFirst("-----BEGIN PUBLIC KEY-----", "").replaceFirst("-----END PUBLIC KEY-----", "").replaceAll("\\s", "");
        byte[] keyBytes = Base64.getDecoder().decode(keyStr);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(keyBytes);
        RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
        // Initialize JWT verifier.
        Algorithm algorithm = Algorithm.RSA256(publicKey, null);
        return JWT.require(algorithm).build();
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        LOGGER.error(String.format("Failed initializing JWT verifier: %s", e.toString()));
        throw new GenerateKeyException("Cannot generate key: ", e);
    }
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) Algorithm(com.auth0.jwt.algorithms.Algorithm) KeyFactory(java.security.KeyFactory) Bean(org.springframework.context.annotation.Bean)

Example 70 with Algorithm

use of com.auth0.jwt.Algorithm in project bank-of-anthos by GoogleCloudPlatform.

the class JWTVerifierGenerator method generateJWTVerifier.

@Bean(name = "verifier")
public JWTVerifier generateJWTVerifier(@Value("${PUB_KEY_PATH}") final String publicKeyPath) {
    // load public key from file
    try {
        LOGGER.debug("Generating JWT token verifier");
        String keyStr = new String(Files.readAllBytes(Paths.get(publicKeyPath)));
        keyStr = keyStr.replaceFirst("-----BEGIN PUBLIC KEY-----", "").replaceFirst("-----END PUBLIC KEY-----", "").replaceAll("\\s", "");
        byte[] keyBytes = Base64.getDecoder().decode(keyStr);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(keyBytes);
        RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
        // Initialize JWT verifier.
        Algorithm algorithm = Algorithm.RSA256(publicKey, null);
        return JWT.require(algorithm).build();
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        LOGGER.error(String.format("Failed initializing JWT verifier: %s", e.toString()));
        throw new GenerateKeyException("Cannot generate key: ", e);
    }
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) Algorithm(com.auth0.jwt.algorithms.Algorithm) KeyFactory(java.security.KeyFactory) Bean(org.springframework.context.annotation.Bean)

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