首先要导入对应的Maven依赖
对Token进行加密
先定义两个常量
private final static String secret = "yunhao"; // 目的是加盐,内容随意
private JWTVerifier verifier;
// 加密过程
public ApiTokenResult createToken(Integer userId, String userUuid) {
try {
Algorithm algorithm = Algorithm.HMAC256(secret);
String token = JWT.create().withClaim("uid", userUuid).sign(algorithm); // 创建token
ApiTokenResult result = new ApiTokenResult(userId.toString(), userUuid, token);
redisTemplete.boundValueOps(userUuid).set(result, Constants.TOKEN_EXPIRES_DAY, TimeUnit.DAYS);
return result;
} catch (Exception exception) {
throw new AppRuntimeException("token生成失败");
}
}
// 解密过程
public ApiTokenResult checkToken(String token) {
if (StringUtils.isBlank(token)) {
return null;
}
DecodedJWT jwt = null;
try {
if (verifier == null) {
Algorithm algorithm = Algorithm.HMAC256(secret);
verifier = JWT.require(algorithm).build(); //Reusable verifier instance
}
jwt = verifier.verify(token);
String uid = jwt.getClaims().get("uid").asString(); // 获取到uuid
ApiTokenResult result = (ApiTokenResult) redisTemplete.boundValueOps(uid).get();
return result;
} catch (Exception e) {
_logger.error("checkToken error : {}", e.getLocalizedMessage());
return null;
}
}
参考网址:https://blog.csdn.net/zhangchao19890805/article/details/79191177