ServiceAuthRestInterceptor.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.yaozhitech.spring5.intercept;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Value;
  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.provider.AuthServerProvider;
  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 AuthServerProvider clientAuthProvider;
  25. @Value("${spring.application.name}")
  26. private String applicationName;
  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-token");
  43. logger.info(token);
  44. String client = request.getHeader("x-auth-client");
  45. if (token.equals("gateway")) {
  46. return super.preHandle(request, response, handler);
  47. }
  48. try {
  49. String uniqueName = JwtUtils.getUsername(client);
  50. if (Boolean.TRUE.equals(clientAuthProvider.verify(applicationName, uniqueName.split("\\.")[0], uniqueName.split("\\.")[1]))) {
  51. return super.preHandle(request, response, handler);
  52. }
  53. } catch (Exception e) {
  54. log.error(e.getMessage(), e);
  55. throw new ClientForbiddenException("Client verfy error");
  56. }
  57. throw new ClientForbiddenException("Client is Forbidden!");
  58. }
  59. }