美文网首页
拦截器实现限制频繁访问,避免恶意攻击,反爬虫

拦截器实现限制频繁访问,避免恶意攻击,反爬虫

作者: 创奇 | 来源:发表于2020-04-03 23:20 被阅读0次

    流程:拦截器对每个请求进行拦截,把请求的ip+请求方法路径作为key,请求次数作为value存储到redis,相同key则value+1,大于等于限制的访问次数,则拦截请求限制访问。

    获取ip工具类

    
    package com.tale.subject.common.util;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * @Author tale
     * @Date 2019/12/18 20:38
     * @Version 1.0
     */
    public class IPUtil {
    
        /**
         * 获取IP地址
         * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
         * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
         */
        public static String getIpAddr(HttpServletRequest request) {
            String ip = null;
            try {
                ip = request.getHeader("x-forwarded-for");
                if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                    // 多次反向代理后会有多个ip值,第一个ip才是真实ip
                    if( ip.indexOf(",")!=-1 ){
                        ip = ip.split(",")[0];
                    }
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_CLIENT_IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("X-Real-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
                System.out.println("ip--->" + ip);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("ip 获取异常-----");
            }
    
            return ip;
        }
    
    
    }
    
    

    访问限制注解:

    
    /**
     * 设置访问限制注解
     * Author: tale
     * Date : 2019/12/18 20:32
     * @Version V1.0
     **/
    @Documented
    @Inherited
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    public @interface VisitLimit {
        // 访问次数限制
        int limit();
        // 时间范围(单位秒)
        int rangeTime();
        // 当触发时限制时间内不能访问(单位秒)
        int expire();
    
    }
    
    

    访问限制拦截器:

    
    import com.tale.subject.common.util.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.HandlerInterceptor;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.lang.reflect.Method;
    
    /**
     * 访问限制拦截器
     * Author: tale
     * Date: 2019/12/18 21:21
     * @Version V1.0
     **/
    public class VisitLimitInterceptor implements HandlerInterceptor {
    
        Logger logger = LoggerFactory.getLogger(VisitLimitInterceptor.class);
    
        @Autowired
        private JedisUtil jedisUtil;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
            if (handler instanceof HandlerMethod){
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                Method method = handlerMethod.getMethod();
    
                // 判断该方法是否含有限制访问注解@VisitLimit
                if (! method.isAnnotationPresent(VisitLimit.class)){
                    return true;
                }
    
                // 获取限制访问注解信息
                VisitLimit visitLimit = method.getAnnotation(VisitLimit.class);
    
                if (visitLimit == null){
                    return true;
                }
                int limit = visitLimit.limit();
                int expireTime = visitLimit.expire();
                int rangeTime = visitLimit.rangeTime();
    
                // ip + 请求的方法路径作为key
                String key = IpUtil.getIpAddress(request) + request.getRequestURI();
    
                Integer currentVisit = null;// 当前访问次数
                String value = jedisUtil.getStr(key);
    
                if (value != null && ! "".equals(value)){
                    currentVisit = Integer.valueOf(value);
                }
    
                if (currentVisit == null){
                    // 第一次请求
                    jedisUtil.set(key, "1", rangeTime);
                }else if (currentVisit < limit){
                    // 在指定时间(rangeTime)内请求相同的方法,访问次数+1
                    Integer times = currentVisit + 1;
                    jedisUtil.set(key, times.toString(), rangeTime);
                }else {
                    // 超出限制的访问次数,限制访问。即在expireTime内限制访问
                    jedisUtil.set(key, currentVisit.toString(), expireTime);
    
                    // 要返回的响应消息
                    String msg = "小盆友!你访问太频繁了!请在" + expireTime + "秒后再访问";
                    int code = ResultCode.VISIT_LIMIT;  // 响应码
    
                    ResponseUtil.responseJson(response, code, msg);
                    return false;
                }
    
    
            }
    
            return true;
        }
    }
    
    

    redis工具类方法:

    /**
         * get
         * @param key
         * @return
         */
        public String getStr(String key){
            try {
                Object value = redisTemplate.opsForValue().get(key);
                if (value != null && ! "".equals(value)){
                    return (String) value;
                }
                return "";
            }catch (Exception e){
                e.printStackTrace();
                return "";
            }
    
        }
    
        /**
         *
         * @param key
         * @param value
         * @param expireTime 过期时间单位秒
         * @return
         */
        public boolean set(String key, String value, int expireTime){
            try {
                redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
    
                return true;
            }catch (Exception e){
                return false;
            }
        }
    
    

    可在方法上使用注解:

    /**
    * 限制频繁登录
    * limit 3 rangeTime 5 表示在5秒内请求3次登录则
    * 会被限制访问,在60秒后才可以访问
    */
    @VisitLimit(limit = 3, rangeTime = 5, expire = 60)
     public R login(@RequestBody UserModel userModel){
    
    // 此处省略
    
     }
    
    

    相关文章

      网友评论

          本文标题:拦截器实现限制频繁访问,避免恶意攻击,反爬虫

          本文链接:https://www.haomeiwen.com/subject/bwalphtx.html