1、 新增一个拦截器JwtInterceptor
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.shown.shownmp.domain.User;
import com.shown.shownmp.exception.BusinessException;
import com.shown.shownmp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
* @author shown
* @date 2023/12/7 9:23
*/
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
public static final int ERROR_CODE_401 = 401;
@Autowired
private UserService userService;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle method is called");
String token = request.getHeader("Authorization");
if (StrUtil.isBlank(token)){
token = request.getParameter("token");
}
//执行认证
if (StrUtil.isBlank(token)){
throw new BusinessException(ERROR_CODE_401,"无token,请重新登录!");
}
//获取token中的userId
String userId;
User user;
try {
userId = JWT.decode(token).getAudience().get(0);
user = userService.getById(Integer.parseInt(userId));
// 获取 JWT 的过期时间
Date expirationDate = JWT.decode(token).getExpiresAt();
if (expirationDate != null && expirationDate.before(new Date())){
throw new BusinessException(ERROR_CODE_401,"token已过期,请重新登录!");
}
} catch (Exception e) {
String errMsg = "token验证失败,请重新登录";
log.error(errMsg + ", token=" + token, e);
throw new BusinessException(ERROR_CODE_401, errMsg);
}
if (user == null){
throw new BusinessException(ERROR_CODE_401,"用户不存在,请重新登录!");
}
//用户密码加签验证 token,对应TokenUtils,java中的.sign(Algorithm.HMAC256(sign))
// 以 password 作为 token 的密钥
try {
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserPassword())).build();
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new BusinessException(ERROR_CODE_401,"token验证失败,请重新登录!");
}
return true;
}
}
2、新增一个TokenUtils
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shown.shownmp.domain.User;
import com.shown.shownmp.exception.BusinessException;
import com.shown.shownmp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
/**
* @author shown
* @date 2023/12/7 9:30
*/
@Component
@Slf4j
public class TokenUtils {
private static UserService staticUserService;
@Resource
private UserService userService;
@PostConstruct
public void setUserService() {
staticUserService = userService;
}
/**
* 生成token
*
* @return
*/
public static String getToken(String userId, String sign) {
return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
.withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
.sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
}
/**
* 获取当前登录的用户信息
*
* @return user对象
*
*/
public static User getCurrentUser() {
String token = null;
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
token = request.getHeader("Authorization");
if (StrUtil.isBlank(token)) {
token = request.getParameter("token");
}
if (StrUtil.isBlank(token)) {
log.error("获取当前登录的token失败, token: {}", token);
return null;
}
//获取用户id
String userId = String.valueOf(JWT.decode(token).getAudience().get(0));
//检验token是否有效
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("token",token);
User user = staticUserService.getOne(queryWrapper);
if (user == null){
log.error("token不存在!userid={}",userId);
return null;
}
return user;
} catch (Exception e) {
log.error("获取当前登录的管理员信息失败, token={}", token, e);
return null;
}
}
}
3、配置文件(有部分注意点已打注释)
import com.shown.shownmp.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author shown
* @date 2023/12/7 9:20
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
JwtInterceptor jwtInterceptor;
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 指定controller统一的接口前缀
configurer.addPathPrefix("", clazz -> clazz.isAnnotationPresent(RestController.class));
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//增加了全局api后就不需要在这儿加上api前缀会导致路径不匹配
// registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**")
// .excludePathPatterns("/api/user/login", "/api/user/register");
registry.addInterceptor(jwtInterceptor).addPathPatterns("/**")
.excludePathPatterns("/user/login", "/user/register");
}
}