ServiceAuthRestInterceptor.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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.yaozhitech.spring5.annotation.IgnoreClientToken;
  11. import com.yaozhitech.spring5.common.exception.auth.ClientForbiddenException;
  12. import com.yaozhitech.spring5.config.ServiceAuthConfig;
  13. import com.yaozhitech.spring5.utils.JwtUtils;
  14. import lombok.extern.slf4j.Slf4j;
  15. /**
  16. * 微服务之间的认证
  17. * @author EDZ
  18. *
  19. */
  20. @Slf4j
  21. public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {
  22. private Logger logger = LoggerFactory.getLogger(ServiceAuthRestInterceptor.class);
  23. // @Autowired
  24. // private ServiceAuthUtil serviceAuthUtil;
  25. //
  26. // @Autowired
  27. private ServiceAuthConfig serviceAuthConfig;
  28. private List<String> allowedClient = Arrays.asList("admin", "order", "gateway");
  29. @Override
  30. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  31. HandlerMethod handlerMethod = (HandlerMethod) handler;
  32. // ip
  33. // if (ClientUtil.isLocalhost(request)) {
  34. // return super.preHandle(request, response, handler);
  35. // }
  36. // 配置该注解,说明不进行服务拦截
  37. IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);
  38. if (annotation == null) {
  39. annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
  40. }
  41. if(annotation != null) {
  42. return super.preHandle(request, response, handler);
  43. }
  44. String token = request.getHeader("x-auth-client");
  45. logger.info(token);
  46. if (token.equals("gateway")) {
  47. return super.preHandle(request, response, handler);
  48. }
  49. try {
  50. String uniqueName = JwtUtils.getUsername(token);
  51. for (String client : allowedClient) {
  52. if (client.equals(uniqueName.split("\\.")[0])) {
  53. return super.preHandle(request, response, handler);
  54. }
  55. }
  56. } catch (Exception e) {
  57. log.error(e.getMessage(), e);
  58. throw new ClientForbiddenException("Client verfy error");
  59. }
  60. throw new ClientForbiddenException("Client is Forbidden!");
  61. }
  62. }