可以去看一下我上一篇文章,使用token和redis验证
1、JWT
1️⃣什么是jwt
2️⃣jwt认证流程
3️⃣jwt的组成
2、引入依赖
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
3、封装
1️⃣生成
2️⃣提取
3️⃣验证
public static DecodedJWT getToken(String token){
try{
Algorithm algorithm=Algorithm.HMAC256(SECRET);
JWTVerifier build=JWT.require(algorithm).build();//验证对象
return build.verify(token);
}catch (SignatureVerificationException e){
ThrowException.verify(true,400,"无效签名!");
return null;
}catch (TokenExpiredException e){
ThrowException.verify(true,401,"token过期!");
return null;
}catch (AlgorithmMismatchException e){
ThrowException.verify(true,400,"算法不一致!");
return null;
}catch (Exception e){
ThrowException.verify(true,400,"token无效");
return null;
}
}
总结
jwt对比用 token和redis,最大优点,是他可以存储载荷,不需要在去数据库而外获取,减少了代码量
当然他是可以结合springboot使用呢