1.在写拦截器的时候获取 通过HandlerMethod handlerMethod=(HandlerMethod)object 获取请求方法,然后判断是否为请求接口方法的时候出错
先贴出拦截器代码,我是一个初级菜鸡,此代码来自于网络其他博客仿写和修改,具体有些不记得出处了,原博客应该没有错误,是自己太粗心导致的错误😂。
package com.zhou.bjgl.bjgl.Interceptor;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.zhou.bjgl.bjgl.exception.BwException;
import com.zhou.bjgl.bjgl.exception.BwExceptionEnum;
import com.zhou.bjgl.bjgl.myAnnotations.UserLoginToken;
import com.zhou.bjgl.bjgl.req.UserReq;
import com.zhou.bjgl.bjgl.resp.user.BUserForInfoResp;
import com.zhou.bjgl.bjgl.resp.user.BUserForQueryResp;
import com.zhou.bjgl.bjgl.service.CommonService;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* @ClassName: AuthenticationInterceptor
* @Description:
* @Author: zhou
* @Date: 2022/2/25 14:08
*/
public class AuthenticationInterceptor implements HandlerInterceptor {
@Resource
private CommonService commonService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
throws Exception {
String token = request.getHeader("x-token");
// 如果不是映射到方法直接通过
if(!(object instanceof HandlerMethod)){
return true;
}
HandlerMethod handlerMethod=(HandlerMethod)object;
Method method = handlerMethod.getMethod();
//检查有没有需要用户权限的注解 @UserLoginToken
if(method.isAnnotationPresent(UserLoginToken.class)){
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if(userLoginToken.required()){
//开始认证
if(token==null){
throw new BwException(BwExceptionEnum.NO_TOKEN);
}
//拿到token中的userId
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (Exception e) {
throw new RuntimeException("401");
}
UserReq userReq = new UserReq();
userReq.setUsername(userId);
BUserForInfoResp user = commonService.getUserInfo(userReq);
if(user==null){
throw new BwException(BwExceptionEnum.USER_NOT_EXIST);
}
//验证token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token);
} catch (Exception e) {
throw new RuntimeException("401");
}
return true;
}
}
return true;
}
}
有没有发现哪里出错了,没错就是HandlerMethod的包导入错误了。
正确的包应该是:
import org.springframework.web.method.HandlerMethod;
关于另一个包的同名类,我目前还不知道具体作用是什么。