ServiceAuthRestInterceptor.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 client = request.getHeader("x-auth-client");
  43. try {
  44. String uniqueName = JwtUtils.getUsername(client);
  45. if (Boolean.TRUE.equals(clientAuthProvider.verify(applicationName, uniqueName.split("\\.")[0], uniqueName.split("\\.")[1]))) {
  46. return super.preHandle(request, response, handler);
  47. }
  48. } catch (Exception e) {
  49. log.error(e.getMessage(), e);
  50. throw new ClientForbiddenException("Client verfy error");
  51. }
  52. throw new ClientForbiddenException("Client is Forbidden!");
  53. }
  54. }