import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.guanyu.common.client.IpCheckClien;
import com.guanyu.report.server.handler.AuthVerifyException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;
/**
* 根据IP地址过滤Controller接口是否可调用
*
* @author guohj
*/
@Aspect
@Component
@Slf4j
public class JobAuthAspect {
@Resource
private IpCheckClien ipCheckClien;
@ApolloJsonValue(value = "${job.auth.method.list:['/test/testmonth']}")
private List<String> jobMethods;
@ApolloJsonValue(value = "${job.auth.enabled:true}")
private boolean jobAuthEnabled;
/**
* 匹配所有Controller的方法
*/
@Pointcut("execution(* com.guanyu.report.server.controller..*.*(..))")
public void controllerMethods() {
}
@Before("controllerMethods()")
public void cutProcess(JoinPoint joinPoint) throws Exception {
// 接收到请求
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录请求的地址
log.info("JobAuthAspect URL:" + request.getRequestURL().toString());
if (jobAuthEnabled && jobMethods.contains(request.getServletPath()) && !ipCheckClien.checkIp(request)) {
throw new AuthVerifyException("非法请求");
}
}
@AfterThrowing(value = "controllerMethods()", throwing = "e")
public void afterThrow(JoinPoint joinPoint, Exception e) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
log.error("JobAuthAspect异常拦截, 方法名为: " + method.getName() + ", 异常信息为: " + e.getMessage());
}
}
07-03
217
12-15
1530
06-12
718
08-13
991