Search in sources :

Example 86 with JWT

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

the class JWTAuthenticator method extractClaimFromBearerToken.

Claim extractClaimFromBearerToken(final String bearerToken, final String claimName) {
    final DecodedJWT jwt;
    try {
        jwt = verifier.verify(bearerToken);
    } catch (JWTVerificationException e) {
        throw new AuthenticationException("Unable to decode or verify JWT bearer token", e);
    }
    final Claim claim = jwt.getClaim(claimName);
    if (claim.isNull()) {
        throw new AuthenticationException("Unable to extract account id claim from JWT bearer token");
    }
    return claim;
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Example 87 with JWT

use of com.auth0.android.jwt.JWT 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 88 with JWT

use of com.auth0.android.jwt.JWT in project kikaha.rocker by jmilagroso.

the class Security method valid.

/**
 * Validates token
 * @param token The token string parameter.
 * @param id The id string/integer parameter.
 * @param claim The claim string parameter.
 * @param issuer The issuer string parameter.
 * @return boolean Is valid.
 */
public boolean valid(String token, String id, String claim, String issuer) {
    boolean valid = false;
    try {
        verifier = JWT.require(algorithm).withJWTId(id).withClaim("name", claim).withIssuer(issuer).build();
        DecodedJWT jwt = verifier.verify(token);
        valid = true;
    } catch (Exception e) {
        throw new IllegalStateException(e.getLocalizedMessage());
    }
    return valid;
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 89 with JWT

use of com.auth0.android.jwt.JWT in project Team_BbungCles_Devnity_BE by prgrms-web-devcourse.

the class JwtAuthenticationFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        String token = getToken(request);
        if (Objects.nonNull(token)) {
            try {
                Jwt.Claims claims = verify(token);
                log.debug("Jwt parse result: {}", claims);
                String email = claims.email;
                Long userId = claims.userId;
                GrantedAuthority authority = getAuthorities(claims);
                if (Objects.nonNull(email) && !email.isEmpty() && userId != null && authority != null) {
                    JwtAuthenticationToken authentication = new JwtAuthenticationToken(new JwtAuthentication(token, userId, email), null, authority);
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (TokenExpiredException tokenExpiredException) {
                request.setAttribute("exception", AuthErrorCode.TOKEN_EXPIRED.getCode());
            } catch (Exception e) {
                request.setAttribute("exception", AuthErrorCode.INVALID_TOKEN.getCode());
                log.warn("Jwt processing failed: {}", e.getMessage());
            }
        }
    } else {
        log.debug("SecurityContextHolder not populated with security token, as it already contained: '{}'", SecurityContextHolder.getContext().getAuthentication());
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) WebAuthenticationDetailsSource(org.springframework.security.web.authentication.WebAuthenticationDetailsSource) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException)

Example 90 with JWT

use of com.auth0.android.jwt.JWT 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)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)305 Test (org.junit.Test)217 Algorithm (com.auth0.jwt.algorithms.Algorithm)110 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)82 JWTVerifier (com.auth0.jwt.JWTVerifier)79 IOException (java.io.IOException)60 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)54 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)53 Date (java.util.Date)50 Claim (com.auth0.jwt.interfaces.Claim)36 RSAPublicKey (java.security.interfaces.RSAPublicKey)34 ECPublicKey (java.security.interfaces.ECPublicKey)27 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)26 HashMap (java.util.HashMap)25 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)20 Instant (java.time.Instant)20 JsonObject (com.google.gson.JsonObject)19 ServletException (javax.servlet.ServletException)19 JWT (com.auth0.jwt.JWT)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18