123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- package com.yaozhitech.spring5.intercept;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.method.HandlerMethod;
- import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
- import com.yaozhitech.spring5.annotation.IgnoreClientToken;
- import com.yaozhitech.spring5.common.exception.auth.ClientForbiddenException;
- import com.yaozhitech.spring5.provider.AuthServerProvider;
- import com.yaozhitech.spring5.utils.JwtUtils;
- import lombok.extern.slf4j.Slf4j;
- /**
- * 微服务之间的认证
- * @author EDZ
- *
- */
- @Slf4j
- public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {
- private Logger logger = LoggerFactory.getLogger(ServiceAuthRestInterceptor.class);
- @Autowired
- private AuthServerProvider clientAuthProvider;
-
- @Value("${spring.application.name}")
- private String applicationName;
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- HandlerMethod handlerMethod = (HandlerMethod) handler;
- // ip
- // if (ClientUtil.isLocalhost(request)) {
- // return super.preHandle(request, response, handler);
- // }
-
- // 配置该注解,说明不进行服务拦截
- IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);
- if (annotation == null) {
- annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
- }
- if(annotation != null) {
- return super.preHandle(request, response, handler);
- }
- String token = request.getHeader("x-auth-token");
- logger.info(token);
-
- String client = request.getHeader("x-auth-client");
-
- if (token.equals("gateway")) {
- return super.preHandle(request, response, handler);
- }
- try {
- String uniqueName = JwtUtils.getUsername(client);
- if (Boolean.TRUE.equals(clientAuthProvider.verify(applicationName, uniqueName.split("\\.")[0], uniqueName.split("\\.")[1]))) {
- return super.preHandle(request, response, handler);
- }
-
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- throw new ClientForbiddenException("Client verfy error");
- }
-
- throw new ClientForbiddenException("Client is Forbidden!");
- }
- }
|