1、安装依赖
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
2、自定义拦截器jwtInterceptor
2.1 、判断token是否在请求头中携带或者是否拼接到了url中,获取到url
String token = request.getHeader("token");
if(StrUtil.isBlank(token)){
token = request.getParameter("token");
}
if(StrUtil.isBlank(token)){
throw new ServiceException("请登录", "401");
}
2.2、解码获取token中的userID,并判断数据库中是否存在
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j){
throw new ServiceException("请登录", "401");
}
Employee user = employeeMapper.selectById(userId);
if(user == null){
throw new ServiceException("用户为注册","402");
}
2.3、用户密码加签后验证token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try{
jwtVerifier.verify(token);
}catch (JWTDecodeException e){
throw new ServiceException("请登录", "401");
}
return true;
2.4、整体代码
package com.example.kauyuan_classroom2.common;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com