FeignAuthenticationInterceptor

    xiaoxiao2025-04-02  11

    /** * @ClassName: AuthenticationInterceptor * @Description: * @Author: QIUJIAQING * @Date: 2019-03-29 16:53 * @Version:1.0 **/ @Slf4j public class FeignAuthenticationInterceptor implements HandlerInterceptor { @Autowired private MircoserviceInfoService mircoserviceInfoService; @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { String token = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);// 从 http 请求头中取出 token // 如果不是映射到方法直接通过 if (!(object instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) object; Method method = handlerMethod.getMethod(); if (method.isAnnotationPresent(PassToken.class)) { PassToken passToken = method.getAnnotation(PassToken.class); if (passToken.required()) { return true; } } //检查有没有需要微服务权限的注解 if (method.isAnnotationPresent(MSToken.class)) { MSToken msToken = method.getAnnotation(MSToken.class); if (msToken.required()) { // 执行认证 if (token == null) { throw new SystemException(SystemException.DESC000021, SystemException.DESC000021); } String mircoserviceName; try { mircoserviceName = JWT.decode(token).getAudience().get(0); } catch (JWTDecodeException j) { throw new SystemException(SystemException.CODE000022, SystemException.DESC000022); } MircoserviceInfo mircoserviceInfo = new MircoserviceInfo(); mircoserviceInfo.setMircoserviceName(mircoserviceName); MircoserviceInfo resultInfo = mircoserviceInfoService.getMircoserviceInfo(mircoserviceInfo); if (resultInfo == null) { throw new SystemException(SystemException.CODE030002, SystemException.DESC030002); } // 验证 token JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(resultInfo.getMircoserviceName() + resultInfo.getPassword())).build(); try { jwtVerifier.verify(token); } catch (JWTVerificationException e) { throw new SystemException(SystemException.CODE000022, SystemException.DESC000022); } 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 { } }
    最新回复(0)