目录
什么拦截器?
拦截器的基本使用
注册拦截器中的路径配置
拦截器的执行流程
什么拦截器?
拦截器的基本使用
1.定义拦截器,实现Handlerlnterceptor接口,重写方法
(Ctrl 加 o 选择重写的方法)
Component//注入注解
public class JwtInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);
@Resource
private AdminService adminService;
@Resource
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 1. 从http请求的header中获取token
String token = request.getHeader(Constants.TOKEN);
if (ObjectUtil.isEmpty(token)) {
// 如果没拿到,从参数里再拿一次
token = request.getParameter(Constants.TOKEN);
}
// 2. 开始执行认证
if (ObjectUtil.isEmpty(token)) {
throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
}
Account account = null;
try {
// 解析token获取存储的数据
String userRole = JWT.decode(token).getAudience().get(0);
String userId = userRole.split("-")[0];
String role = userRole.split("-")[1];
// 根据userId查询数据库
if (RoleEnum.ADMIN.name().equals(role)) {
account = adminService.selectById(Integer.valueOf(userId));
}else if (RoleEnum.USER.name().equals(role)) {
account = userService.selectById(Integer.valueOf(userId));
}
} catch (Exception e) {
throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
}
if (ObjectUtil.isNull(account)) {
throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
}
try {
// 用户密码加签验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(account.getPassword())).build();
jwtVerifier.verify(token); // 验证token
} catch (JWTVerificationException e) {
throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
}
return true;
}
}
2.注册拦截器(新的配置类)重写WebMvcConfigurer中的方法,addInterceptors方法
然后调用
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private JwtInterceptor jwtInterceptor;//从中注入拦截器
// 加自定义拦截器JwtInterceptor,设置拦截规则
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor).addPathPatterns("/**")//拦截所有资源
.excludePathPatterns("/")
.excludePathPatterns("/login")
.excludePathPatterns("/register")
.excludePathPatterns("/files/**");
}
}
注册拦截器中的路径配置
.addPathPatterns(拦截的路径)
.excludePathPatterns(不需要拦截的路径)