![在这里插入图片描述](https://img-blog.csdnimg.cn/88a7cd0e18b04548af5e7183f6ce1d64.png
一、导入JWT依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
二、写token工具类
@Slf4j
@Component
public class TokenUtils {
@Autowired
private UserMapper userMapper;
private static UserMapper staticUserMapper;
@PostConstruct
public void init() {
staticUserMapper = userMapper;
}
public static String getToken(User user) {
return JWT.create()
.withExpiresAt(DateUtil.offsetDay(new Date(), 1))
.withAudience(user.getId().toString())
.sign(Algorithm.HMAC256(user.getPassword()));
}
public static User getUser() {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("token");
String aud = JWT.decode(token).getAudience().get(0);
Integer userId = Integer.valueOf(aud);
return staticUserMapper.selectById(userId);
} catch (Exception e) {
log.error("解析token失败", e);
return null;
}
}
}
三、自定义异常
1.自定义异常
@Data
public class ServiceException extends RuntimeException {
private String code;
public ServiceException(String code, String msg) {
super(msg);
this.code = code;
}
}
2.抛出该异常时,做出的反应
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ServiceException.class)
@ResponseBody
public Result handle(ServiceException se){
return Result.error(se.getCode(), se.getMessage());
}
}
抛出该异常后,后端返回该异常的code和message
四、拦截器
1.编写jwt拦截器
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private IUserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String token = request.getHeader("token");
if(!(handler instanceof HandlerMethod)){
return true;
}
if (StrUtil.isBlank(token)) {
throw new ServiceException(Constants.CODE_401, "无token,请重新登录");
}
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录");
}
User user = userService.getById(userId);
if (user == null) {
throw new ServiceException(Constants.CODE_401, "用户不存在,请重新登录");
}
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new ServiceException(Constants.CODE_401, "token验证失败,请重新登录");
}
return true;
}
}
2.添加该拦截器
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user/login","/user/register");
}
@Bean
public JwtInterceptor jwtInterceptor(){
return new JwtInterceptor();
}
}
五、前端vue实现无token退出登录
在封装类中添加
1.设置请求头
const request = axios.create({
baseURL: '/api',
timeout: 5000
})
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null;
if(user){
config.headers['token'] = user.token;
}
return config
}, error => {
return Promise.reject(error)
});
在登录的时候记得本地存储
2.response 拦截器
request.interceptors.response.use(
response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
if (res.code==='401'){
ElMessage.error("token验证失败!请重新登录");
}
return res;
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
效果:
|