handler instanceof HandlerMethod 一直为false 是因为导错了包
应该导入:
import org.springframework.web.method.HandlerMethod;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 从http请求头中取出token
final String token = request.getHeader(JwtUtil.AUTH_HEADER_KEY);
//如果不是映射到方法,直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
//如果是方法探测,直接通过
if (HttpMethod.OPTIONS.equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return true;
}
//如果方法有JwtIgnore注解,直接通过
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method=handlerMethod.getMethod();
if (method.isAnnotationPresent(JwtIgnore.class)) {
JwtIgnore jwtIgnore = method.getAnnotation(JwtIgnore.class);
if(jwtIgnore.value()){
return true;
}
}
// LocalAssert.isStringEmpty(token, "token为空,鉴权失败!");
if (StringUtils.isEmpty(token)){
throw new BaseException("token为空,鉴权失败!");
}
//验证,并获取token内部信息
Claims claims = JwtUtil.parseJWT(token);
String userToken = claims.getSubject();
//将token放入本地缓存
WebContextUtil.setUserToken(userToken);
return true;
}