SpringBoot自定义过滤器实现高频IP限制访问

代码走查的时候走查老师提出建议对高频ip做限制,防止不法ip攻击,去网上看了很多方法,最多的就是自定义注解,然后定义一个注解的实现类利用aop去验证该限制接口的请求ip是否符合,但是缺点就是我们不可能每一个接口都要去加注解。
还有一种方法就是利用过滤器去验证每一个请求的ip,原文地址,感谢东哥(我们不生产代码,我们只是代码的搬运工_
下面附上代码:

过滤器:统计用户访问次数,记录访问时间、封禁时间
监听器:工程运行时初始化IP存储器(此处用的Map)

自定义过滤器:

/**
 * 自定义过滤器,用来判断IP访问次数是否超限
 * 如果前台用户访问网站的频率过快,则判定该ip恶意刷新操作,
 * 限制该IP的访问,1小时后自己解除限制
 */
@WebFilter(urlPatterns = "/*")
public class MyIpFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(MyIpFilter.class);

    /**
     * 默认限制时间(单位:ms)
     */
    private static final long LIMITED_TIME_MILLIS = 60 * 60 * 1000;

    /**
     * 用户连续访问最高阀值,超过该值则认定为恶意操作的IP,进行限制
     */
    private static final int LIMIT_NUMBER = 50;

    /**
     * 用户访问最小安全时间,在该时间内如果访问次数大于阀值,则记录为恶意IP,否则视为正常访问
     */
    private static final int MIN_SAFE_TIME = 1000;

    private FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) {
        this.config = filterConfig;    //设置属性filterConfig
    }

    /**
     * (non-Javadoc)
     *
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @SuppressWarnings("unchecked")
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        ServletContext context = config.getServletContext();
        Map limitedIpMap = (Map) context.getAttribute("limitedIpMap");
        filterLimitedIpMap(limitedIpMap);
        String ip = request.getRemoteHost();
        // 判断是否是被限制的IP,如果是则跳到异常页面
        if (isLimitedIP(limitedIpMap, ip)) {
            long limitedTime = limitedIpMap.get(ip) - System.currentTimeMillis();
            request.setAttribute("remainingTime", ((limitedTime / 1000) + (limitedTime % 1000 > 0 ? 1 : 0)));
            logger.error("IP访问过于频繁=>:" + ip);
            request.getRequestDispatcher("/error/requestLimit").forward(request, response);
            return;
        }
        // 获取IP存储器
        Map ipMap = (Map) context.getAttribute("ipMap");
        // 判断存储器中是否存在当前IP,如果没有则为初次访问,初始化该ip
        // 如果存在当前ip,则验证当前ip的访问次数
        // 如果大于限制阀值,判断达到阀值的时间,如果不大于[用户访问最小安全时间]则视为恶意访问,跳转到异常页面
        if (ipMap.containsKey(ip)) {
            Long[] ipInfo = ipMap.get(ip);
            ipInfo[0] = ipInfo[0] + 1;
            logger.info("当前IP第[" + (ipInfo[0]) + "]次访问");
            if (ipInfo[0] > LIMIT_NUMBER) {
                Long ipAccessTime = ipInfo[1];
                Long currentTimeMillis = System.currentTimeMillis();
                if (currentTimeMillis - ipAccessTime <= MIN_SAFE_TIME) {
                    limitedIpMap.put(ip, currentTimeMillis + LIMITED_TIME_MILLIS);
                    request.setAttribute("remainingTime", ((LIMITED_TIME_MILLIS / 1000) + (LIMITED_TIME_MILLIS % 1000 > 0 ? 1 : 0)));
                    logger.error("IP访问过于频繁:" + ip);
                    request.getRequestDispatcher("/error/requestLimit").forward(request, response);
                    return;
                } else {
                    initIpVisitsNumber(ipMap, ip);
                }
            }
        } else {
            initIpVisitsNumber(ipMap, ip);
            logger.info("首次访问该网站");
        }
        context.setAttribute("ipMap", ipMap);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @param limitedIpMap
     * @Description 过滤受限的IP,剔除已经到期的限制IP
     */
    private void filterLimitedIpMap(Map limitedIpMap) {
        if (limitedIpMap == null) {
            return;
        }
        Set keys = limitedIpMap.keySet();
        Iterator keyIt = keys.iterator();
        long currentTimeMillis = System.currentTimeMillis();
        while (keyIt.hasNext()) {
            long expireTimeMillis = limitedIpMap.get(keyIt.next());
            if (expireTimeMillis <= currentTimeMillis) {
                keyIt.remove();
            }
        }
    }

    /**
     * @param limitedIpMap
     * @param ip
     * @return true : 被限制 | false : 正常
     * @Description 是否是被限制的IP
     */
    private boolean isLimitedIP(Map limitedIpMap, String ip) {

        if (limitedIpMap.containsKey(ip)) {
            return true;
        }
        return false;
    }

    /**
     * 初始化用户访问次数和访问时间
     *
     * @param ipMap
     * @param ip
     */
    private void initIpVisitsNumber(Map ipMap, String ip) {
        Long[] ipInfo = new Long[2];
        ipInfo[0] = 0L;// 访问次数
        ipInfo[1] = System.currentTimeMillis();// 初次访问时间
        ipMap.put(ip, ipInfo);
    }
}

监听器:

@WebListener
public class MyApplicationListener implements ServletContextListener {

    private Logger logger = LoggerFactory.getLogger(MyApplicationListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("liting: contextInitialized");
        logger.info("MyApplicationListener初始化成功");
        ServletContext context = sce.getServletContext();
        // IP存储器
        Map ipMap = new HashMap();
        context.setAttribute("ipMap", ipMap);
        // 限制IP存储器:存储被限制的IP信息
        Map limitedIpMap = new HashMap();
        context.setAttribute("limitedIpMap", limitedIpMap);
        logger.info("ipmap:" + ipMap.toString() + ";limitedIpMap:" + limitedIpMap.toString() + "初始化成功-----");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub
    }
}

然后在SpringBoot启动类添加扫描过滤器

@ServletComponentScan(basePackages = "com.ziding.product.cooperation.requestLimit")

如果被限制后将会转发到新的接口

@RestController
public class RequestLimit {

    /**
     * 对高频ip限制,携带剩余限制时间
     *
     * @param request
     * @return
     */
    @RequestMapping("/error/requestLimit")
    public ResultEntity requestLimitTime(HttpServletRequest request) {
        Object limitTime = request.getAttribute("remainingTime");
        return ResultTemplate.errorData(5001, "IP已被限制,请稍后在试~", limitTime);
    }
}

你可能感兴趣的:(Java)