Aop 根据IP地址过滤Controller接口是否可调用

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());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值