Search in sources :

Example 41 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project bank-of-sirius by nginxinc.

the class JWTVerifierGenerator method generateJWTVerifier.

@Bean(name = "verifier")
@ConditionalOnProperty(value = "jwt.account.authentication.enabled", matchIfMissing = true, havingValue = "true")
public JWTVerifier generateJWTVerifier(@Value("${PUB_KEY_PATH}") final String publicKeyPath) throws IOException {
    // load public key from file
    final Path publicKeyFile = Paths.get(publicKeyPath);
    final String keyContents = new String(Files.readAllBytes(publicKeyFile));
    try {
        final String keyStr = keyContents.replaceFirst("-----BEGIN PUBLIC KEY-----", "").replaceFirst("-----END PUBLIC KEY-----", "").replaceAll("\\s", "");
        final byte[] keyBytes = Base64.getDecoder().decode(keyStr);
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(keyBytes);
        final RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
        // Initialize JWT verifier.
        final Algorithm algorithm = Algorithm.RSA256(publicKey, null);
        final JWTVerifier verifier = JWT.require(algorithm).build();
        LOGGER.debug("Generated JWT token verifier [algorithm={},publicKeyPath={}]", algorithm.getName(), publicKeyFile);
        return verifier;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        final String msg = String.format("Cannot generate JWT key [path=%s]", publicKeyFile);
        throw new GenerateKeyException(msg, e);
    }
}
Also used : Path(java.nio.file.Path) RSAPublicKey(java.security.interfaces.RSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) KeyFactory(java.security.KeyFactory) Bean(org.springframework.context.annotation.Bean) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty)

Example 42 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project Tbed by Hello-hao.

the class JWTUtil method checkToken.

public static JSONObject checkToken(String token) {
    // 验证对象
    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
    JSONObject jsonObject = new JSONObject();
    if (null == token) {
        jsonObject.put("check", false);
        return jsonObject;
    }
    try {
        DecodedJWT verify = jwtVerifier.verify(token);
        Date expiresAt = verify.getExpiresAt();
        jsonObject.put("check", true);
        jsonObject.put("email", verify.getClaim("email").asString());
        jsonObject.put("password", verify.getClaim("password").asString());
        jsonObject.put("uid", verify.getClaim("uid").asString());
    } catch (TokenExpiredException e) {
        e.printStackTrace();
        System.out.println("token认证已过期,请重新登录获取");
        jsonObject.put("check", false);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("token无效");
        jsonObject.put("check", false);
    }
    return jsonObject;
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException)

Example 43 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project UPE_2021_2_Propague by netrometro.

the class TipoParaUsuarioForm method refreshToken.

@GetMapping("/token/refresh")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        try {
            String refresh_token = authorizationHeader.substring(7);
            Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(refresh_token);
            String username = decodedJWT.getSubject();
            Usuario usuario = servico.getUsuario(username);
            String acces_token = com.auth0.jwt.JWT.create().withSubject(usuario.getEmail()).withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("tipo", usuario.getTipos().stream().map(TipoUsuario::getNome).collect(Collectors.joining())).sign(algorithm);
            // response.setHeader("acces_token", token);
            // response.setHeader("refresh_token", refresh_token);
            Map<String, String> map = new HashMap<>();
            map.put("token", acces_token);
            map.put("refresh_token", refresh_token);
            response.setContentType(APPLICATION_JSON_VALUE);
            new ObjectMapper().writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            response.setHeader("error", e.getMessage());
            response.setStatus(403);
            Map<String, String> map = new HashMap<>();
            map.put("error", e.getMessage());
            response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
            new ObjectMapper().writeValue(response.getOutputStream(), map);
        }
    } else {
        throw new RuntimeException("Refresh token is missing");
    }
}
Also used : TipoUsuario(br.com.propague.api.model.TipoUsuario) Usuario(br.com.propague.api.model.Usuario) HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) IOException(java.io.IOException) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 44 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project yyl_example by Relucent.

the class JwtDemo method main.

public static void main(String[] args) throws Exception {
    long currentMillis = System.currentTimeMillis();
    // JWT 生存时间(5秒)
    long ttl = 5000;
    // 生成JWT的时间
    Date iat = new Date(currentMillis);
    // 生成JWT失效时间
    Date exp = new Date(currentMillis + ttl);
    // 签名秘钥
    String secret = "key";
    // 签发人
    String issuer = "root";
    // 算法
    Algorithm algorithm = Algorithm.HMAC256(secret);
    // 本地的密码解码
    JWTCreator.Builder builder = JWT.create();
    // 签发时间
    builder.withIssuedAt(iat);
    // 签发人
    builder.withIssuer(issuer);
    // 过期时间
    builder.withExpiresAt(exp);
    // 主题
    builder.withClaim("subject", "MySubject");
    String token = builder.sign(algorithm);
    System.out.println(token);
    // 解密
    JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();
    DecodedJWT jwt = verifier.verify(token);
    Map<String, Claim> claims = jwt.getClaims();
    NullClaim nullClaim = new NullClaim();
    System.out.println(claims.getOrDefault("subject", nullClaim).asString());
    // 等待5秒
    System.out.println("Wait 5 seconds!");
    Thread.sleep(5000);
    try {
        // 这时候Token已经超时了,会抛出异常
        verifier.verify(token);
    } catch (JWTVerificationException e) {
        System.err.println(e);
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JWTCreator(com.auth0.jwt.JWTCreator) NullClaim(com.auth0.jwt.impl.NullClaim) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Date(java.util.Date) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim)

Example 45 with JWTVerifier

use of com.auth0.jwt.JWTVerifier in project cryptography by norkator.

the class JWT method verifyECDSA256Jwt.

/**
 * Verify elliptic curve based JWT
 *
 * @param publicPem of key pair
 * @param issuer    party name
 * @param token     of created jwt
 * @return DecodedJWT including claims
 * @throws JWTVerificationException thrown if verification fails
 */
public static DecodedJWT verifyECDSA256Jwt(String publicPem, String issuer, final String token) throws JWTVerificationException, InvalidKeySpecException, NoSuchAlgorithmException {
    ECKey publicKey = (ECKey) PEMToKey.getPemPublicKey(publicPem, "ECDSA");
    Algorithm algorithm = Algorithm.ECDSA256(publicKey);
    JWTVerifier verifier = com.auth0.jwt.JWT.require(algorithm).withIssuer(issuer).build();
    return verifier.verify(token);
}
Also used : ECKey(java.security.interfaces.ECKey) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier)

Aggregations

JWTVerifier (com.auth0.jwt.JWTVerifier)115 Algorithm (com.auth0.jwt.algorithms.Algorithm)104 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)100 Test (org.junit.Test)42 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)30 IOException (java.io.IOException)23 JWTVerifier (com.auth0.jwt.interfaces.JWTVerifier)18 RSAPublicKey (java.security.interfaces.RSAPublicKey)15 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)14 Claim (com.auth0.jwt.interfaces.Claim)10 Date (java.util.Date)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HashMap (java.util.HashMap)8 ECKey (java.security.interfaces.ECKey)7 ServletException (javax.servlet.ServletException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 TokenExpiredException (com.auth0.jwt.exceptions.TokenExpiredException)5 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)5 URL (java.net.URL)5 KeyFactory (java.security.KeyFactory)5