栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

利用redis解决恶意刷新和暴力请求

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用redis解决恶意刷新和暴力请求

在实际项目使用中,要考虑服务被恶意请求和暴力攻击的情况,下面的教程,通过intercept和redis针对url+ip在一定时间内访问的次数来将ip禁用,可以根据自己的需求进行相应的修改,来打到自己的目的;

下边代码利用redis在拦截器解决暴力刷新

首先创建一个自定义的拦截器类,也是最核心的代码:

package com.example.springbootredis.config;

import com.alibaba.fastjson.JSON;
import com.example.springbootredis.util.IpAdrressUtil;
import com.example.springbootredis.util.RedisUtil;
import com.example.springbootredis.util.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Slf4j
@Component
@RequiredArgsConstructor
public class IpUrlLimitInterceptor implements HandlerInterceptor {
    private final RedisUtil redisUtil;

    private static final String LOCK_IP_URL_KEY = "lock_ip_";

    private static final String IP_URL_REQ_TIME = "ip_url_times_";

    private static final long LIMIT_TIMES = 5;

    private static final String IP_LOCK_TIME = "60";

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        log.info("request请求地址uri={},ip={}", httpServletRequest.getRequestURI(), IpAdrressUtil.getIpAddr(httpServletRequest));
        if (ipIsLock(IpAdrressUtil.getIpAddr(httpServletRequest))) {
            log.info("ip访问被禁止={}", IpAdrressUtil.getIpAddr(httpServletRequest));
            returnJson(httpServletResponse, JSON.toJSONString(Result.success("ip访问被禁止")));
            return false;
        }
        if (!addRequestTime(IpAdrressUtil.getIpAddr(httpServletRequest), httpServletRequest.getRequestURI())) {
            returnJson(httpServletResponse, JSON.toJSONString(Result.success("ip访问被禁止")));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    
    private Boolean ipIsLock(String ip) {
        if (redisUtil.hasKey(LOCK_IP_URL_KEY + ip)) {
            return true;
        }
        return false;
    }

    
    private Boolean addRequestTime(String ip, String uri) {
        String key = IP_URL_REQ_TIME + ip + uri;
        if (redisUtil.hasKey(key)) {
            // 如果key存在,次数+1
            long time = redisUtil.incr(key, (long) 1);
            log.info("time:{}", time);
            if (time >= LIMIT_TIMES) {
                // 如果超过限制次数,则设置ip被禁用 60秒
                redisUtil.getLock(LOCK_IP_URL_KEY + ip, ip, IP_LOCK_TIME);
                return false;
            }
        } else {
            // ip+uri请求次数为1,1秒后过期
            redisUtil.getLock(key, "1", "1");
            log.info("记录请求次数1");
        }
        return true;
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            log.error("LoginInterceptor response error ---> {}", e.getMessage(), e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}

代码中redis的使用的是分布式锁的形式,这样可以最大程度保证线程安全和功能的实现效果。代码中设置的是1S内同一个接口通过同一个ip访问5次,就将该ip禁用60S,根据自己项目需求可以自己适当修改,实现自己想要的功能;

redis分布式锁的关键代码:

package com.example.springbootredis.util;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;


@Component
@Slf4j
@RequiredArgsConstructor
public class RedisUtil {

    private static final Long SUCCESS = 1L;

    private final RedisTemplate redisTemplate;

    
    public boolean getLock(String lockKey, Object value, String expireTime) {
        boolean ret = false;
        try {
            String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";

            RedisScript redisScript = new DefaultRedisScript<>(script, Long.class);
            Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime);
            log.info("result:{}", result);
            if (SUCCESS.equals(result)) {
                return true;
            }

        } catch (Exception e) {
            log.error("getLock error:{}", e.getMessage(), e);
        }
        return ret;
    }

    
    public boolean releaseLock(String lockKey, String value) {

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        RedisScript redisScript = new DefaultRedisScript<>(script, String.class);

        Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value);
        if (SUCCESS.equals(result)) {
            return true;
        }

        return false;

    }

    
    public Long incr(String key, Long num) {
        return redisTemplate.opsForValue().increment(key, num);
    }

    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

}

最后将上面自定义的拦截器通过registry.addInterceptor添加一下,就生效了;

package com.example.springbootredis.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
@Slf4j
@RequiredArgsConstructor
public class MyWebAppConfig implements WebMvcConfigurer {
    private final IpUrlLimitInterceptor ipUrlLimitInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ipUrlLimitInterceptor).addPathPatterns("
@Slf4j
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {
    @GetMapping("/ip_test")
    public Result tabCnt() {
        return Result.success("成功");
    }
}

一次请求:

模拟暴力请求:

我在浏览器不停刷新,可以看到已经被拦到了。
当然如果有人不停变换IP去刷量,现在做法是拦不到的。
以上代码地址

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937353.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号