关于java:java-jwt令牌的使用

3次阅读

共计 1065 个字符,预计需要花费 3 分钟才能阅读完成。

依赖引入

<dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.18.1</version>
</dependency>

我应用的是 auth0 的 jwt 包。

令牌的生成

public String generateJwtToken(Long userId, Integer level){Algorithm algorithm = Algorithm.HMAC256(salt);
        Date now = new Date();
        String token = JWT.create()
                .withIssuedAt(now)
                .withClaim("userId", userId)
                .withClaim("level", level)
                .withExpiresAt(getExpiredDate(now))
                .sign(algorithm);
        return token;
    }

令牌的生成如以上代码所示,首先指定算法 (须要应用一个随机字符串作为 salt),之后调用链中 withIssuedAt() 设置签发工夫;withClaim()设置 token 中携带的参数,能够是用户名等信息;withExpiresAt()设置 token 到期的工夫点。

令牌解密

public Map<String, Claim> decodeToken(String jwtToken){Algorithm algorithm = Algorithm.HMAC256(salt);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        try {DecodedJWT decodedJWT = jwtVerifier.verify(jwtToken);
            return decodedJWT.getClaims();}catch (Exception e){e.printStackTrace();
            log.error("校验令牌失败");
            throw new UnAuthenticatedException(10004);
        }
    }

解密时应用的算法与 salt 与加密保持一致,之后调用 JWTVerifier 的 verify()办法解密失去 DecodedJWT 对象,它的 getClaims()办法用于取得加密时设置的参数组成的 Map。Map 的 key 为名称,Claim 类的 asInt()、asLong()等办法用于将参数依据类型导出,类型留神放弃与加密时统一。如果 token 不正确或到期 verify()办法会抛出异样。

正文完
 0