import com.alibaba.csp.sentinel.util.StringUtil;
import com.xtw.enums.BizCodeEnum;
import com.xtw.model.LoginUser;
import com.xtw.util.CommonUtil;
import com.xtw.util.JWTUtil;
import com.xtw.util.JsonData;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpStatus.NO_CONTENT.value());
return true;
}
String accessToken = request.getHeader("token");
if(StringUtil.isBlank(accessToken)){
accessToken = request.getParameter("token");
}
Claims claims = JWTUtil.checkJWT(accessToken);
if(claims == null){
// 未登录
CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
return false;
}
Long account_no = Long.parseLong(claims.get("account_no").toString());
String username = claims.get("username").toString();
String pwd = claims.get("pwd").toString();
String phone = claims.get("phone").toString();
String email = claims.get("email").toString();
System.out.println(pwd+""+email);
LoginUser loginUser = LoginUser.builder()
.accountNo(account_no)
.pwd(pwd)
.userName(username)
.phone(phone)
.email(email).build();
threadLocal.set(loginUser);
return true;
}
@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 {
threadLocal.remove();
}
}
配置拦截接口
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
//添加拦截的路径
.addPathPatterns("/FileUpload/upload")
//排除拦截路径
.excludePathPatterns("/register/*","/jwt/token","/jwt/checkJWT");
}
}
标签:拦截器,request,JWT,校验,toString,import,claims,com,public
From: https://www.cnblogs.com/xietingwei/p/17689708.html