ServiceAuthRestInterceptor.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.yaozhitech.spring5.intercept;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.web.method.HandlerMethod;
  9. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  10. import com.alibaba.nacos.client.utils.IPUtil;
  11. import com.yaozhitech.spring5.common.exception.auth.ClientForbiddenException;
  12. import com.yaozhitech.spring5.common.util.ClientUtil;
  13. import com.yaozhitech.spring5.config.ServiceAuthConfig;
  14. /**
  15. * 微服务之间的认证
  16. * @author EDZ
  17. *
  18. */
  19. public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {
  20. private Logger logger = LoggerFactory.getLogger(ServiceAuthRestInterceptor.class);
  21. // @Autowired
  22. // private ServiceAuthUtil serviceAuthUtil;
  23. //
  24. // @Autowired
  25. private ServiceAuthConfig serviceAuthConfig;
  26. private List<String> allowedClient = Arrays.asList("admin", "order", "gateway");
  27. @Override
  28. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  29. HandlerMethod handlerMethod = (HandlerMethod) handler;
  30. // ip
  31. // if (ClientUtil.isLocalhost(request)) {
  32. // return super.preHandle(request, response, handler);
  33. // }
  34. // // 配置该注解,说明不进行服务拦截
  35. // IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);
  36. // if (annotation == null) {
  37. // annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
  38. // }
  39. // if(annotation!=null) {
  40. // return super.preHandle(request, response, handler);
  41. // }
  42. String token = request.getHeader("x-auth-client");
  43. logger.info(token);
  44. // IJWTInfo infoFromToken = serviceAuthUtil.getInfoFromToken(token);
  45. String uniqueName = token;
  46. for(String client:allowedClient){
  47. if(client.equals(uniqueName)){
  48. return super.preHandle(request, response, handler);
  49. }
  50. }
  51. throw new ClientForbiddenException("Client is Forbidden!");
  52. }
  53. }