用于标注需要验证token的contoller
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TokenCheck {
boolean required() default true;
}
直接在方法上加上@TokenCheck
@PostMapping("/edit")
@TokenCheck
public ResultWrapper edit(@RequestBody UmsMember umsMember){
System.out.println("执行了edit");
return umsMemberService.edit(umsMember);
}
用于捕获异常
public class TokenException extends Exception {
public TokenException(String message) {
super(message);
}
}
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
System.out.println("进入了拦截器");
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
// 判断方法中是否有tokencheck注解
if (method.isAnnotationPresent(TokenCheck.class)){
// 获取token注解
TokenCheck annotation = method.getAnnotation(TokenCheck.class);
// 判断token默认值
if (annotation.required()){
// 获取请求token
String token = request.getHeader("token");
// 判断token是否为空
if (StringUtils.isNullOrEmpty(token)){
// 是的话抛出token异常
throw new TokenException("token 为空");
}
// 解析token
try {
JwtUtil.parseToken(token);
} catch (Exception e){
throw new TokenException("token 异常");
}
}
return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
@Configuration
public class AuthInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**");
}
}
这部分就可以再全局异常捕获代码中添加就行了
@RestControllerAdvice
public class GlobalHandler {
@ExceptionHandler(ArithmeticException.class)
public ResultWrapper globalHandle(Exception e){
return ResultWrapper.builder().code(501).msg(e.getMessage()).build();
}
@ExceptionHandler(TokenException.class)
public ResultWrapper tokenCheckHandler(Exception e){
return ResultWrapper.getFailBuilder().code(501).msg(e.getMessage()).build();
}
}