package com.moral.common.interceptor; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.Claim; import com.moral.common.exception.WebAuthException; import com.moral.common.webAnno.PassToken; import com.moral.common.webAnno.UserLoginToken; import com.moral.entity.Account; import com.moral.service.AccountService; import com.moral.service.impl.WebTokenServiceImpl; import org.springframework.util.ObjectUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.Map; /** * @Description: * @Param: Web大屏端拦截器配置 * @return: * @Author: 陈凯裕 * @Date: 2020/9/14 */ public class WebInterceptor implements HandlerInterceptor { @Resource AccountService accountService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { String token = request.getHeader("token"); Enumeration headerNames = request.getHeaderNames(); //如果不是映射到方法则直接通过 if(!(o instanceof HandlerMethod)){ return true; } HandlerMethod handlerMethod = (HandlerMethod)o; Method method = handlerMethod.getMethod(); //如果有passtoken注解则放行 if(method.isAnnotationPresent(PassToken.class)){ PassToken passToken= method.getAnnotation(PassToken.class); //验证注解是否过期 if(passToken.required()) return true; } //判断请求的方法是否需要登录 if(method.isAnnotationPresent(UserLoginToken.class)){ //判断注解是否失效 UserLoginToken loginToken = method.getAnnotation(UserLoginToken.class); if(loginToken.required()){ if(ObjectUtils.isEmpty(token)){ throw new WebAuthException("无token,请重新登陆"); } //获取ID String id = ""; try { Map claims = JWT.decode(token).getClaims(); Claim accountId = claims.get("aid"); id = accountId.asString(); }catch (JWTDecodeException e){ throw new WebAuthException("401,token无效"); } Account account = accountService.getAccountById(Integer.parseInt(id)); if(ObjectUtils.isEmpty(account)){ throw new WebAuthException("用户不存在,请重新登陆"); } //验证token Algorithm algorithm = Algorithm.HMAC256(WebTokenServiceImpl.SECRET); JWTVerifier jwtVerifier = JWT.require(algorithm) .withIssuer("qxpc") .build(); try{ jwtVerifier.verify(token); }catch (JWTVerificationException e){ throw new WebAuthException("401,token过期或者无效"); } return true; } } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }