依赖引入
<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()办法会抛出异样。