package com.example.erp.common.interceptor;
|
|
import cn.hutool.core.util.StrUtil;
|
import com.auth0.jwt.JWT;
|
import com.auth0.jwt.JWTVerifier;
|
import com.auth0.jwt.algorithms.Algorithm;
|
import com.auth0.jwt.exceptions.JWTVerificationException;
|
import com.example.erp.common.CacheUtil;
|
import com.example.erp.common.Constants;
|
import com.example.erp.controller.dto.UserDTO;
|
import com.example.erp.exception.ServiceException;
|
import com.example.erp.service.userInfo.UserService;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.stereotype.Component;
|
import org.springframework.web.method.HandlerMethod;
|
import org.springframework.web.servlet.HandlerInterceptor;
|
|
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletResponse;
|
|
@Component
|
public class JwtInterceptor implements HandlerInterceptor {
|
|
@Autowired
|
private UserService userService;
|
@Autowired
|
private CacheUtil cacheUtil;
|
|
@Override
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
//return HandlerInterceptor.super.preHandle(request, response, handler);
|
/*String token=request.getHeader("token");
|
if(!(handler instanceof HandlerMethod)){
|
return true;
|
}
|
|
if(StrUtil.isBlank(token)){
|
throw new ServiceException(Constants.Code_401,"无token,重新登陆");
|
}
|
String userId;
|
try{
|
userId = JWT.decode(token).getAudience().get(0);
|
}catch (Exception e){
|
throw new ServiceException(Constants.Code_500,"token格式错误");
|
}
|
|
UserDTO getUserDTO = cacheUtil.getCacheData(userId);
|
|
if(getUserDTO != null && !getUserDTO.getToken().equals(token)){
|
throw new ServiceException(Constants.Code_600,"用户在其他位置登陆");
|
}
|
|
|
String password=userService.getUserByID(userId).toLowerCase();
|
//用户密码加签验证
|
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(password)).build();
|
try {
|
jwtVerifier.verify(token);
|
} catch (JWTVerificationException e) {
|
throw new ServiceException(Constants.Code_401,"token验证失败,请重新登陆");
|
}*/
|
return true;
|
}
|
|
}
|