资讯专栏INFORMATION COLUMN

SpringBoot防止大量请求攻击

kel / 1708人阅读

摘要:我们使用测试同学的网站时,就会出现网站无法访问,等错误。所以我们需要加上访问时间限制,防止一个多次访问请求,导致整个网站崩溃。

我们使用Jmeter测试同学的网站时,就会出现网站无法访问,403等错误。

An error occurred.Sorry, the page you are looking for is currently unavailable.Please try again later.If you are the system administrator of this resource then you should check the error log for details.Faithfully yours, nginx.

所以我们需要加上IP访问时间限制,防止一个IP多次访问请求,导致整个网站崩溃。

  • 自定义注解:
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * 自定义注解,用于拦截过于频繁的请求 */@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface AccessLimit {    int seconds();    int maxCount();    boolean needLogin() default true;}
  • 自定义拦截器:
    我采用了抛出自定义异常的方式来解决相同IP多次访问的问题:
    throw new DujiaoshouException(20001,"操作过于频繁");
import com.qykhhr.dujiaoshouservice.exceptionhandler.DujiaoshouException;import com.qykhhr.dujiaoshouservice.mycomment.AccessLimit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.concurrent.TimeUnit;/** * 自定义拦截器 */@Componentpublic class AccessLimtInterceptor implements HandlerInterceptor {    @Autowired    private RedisTemplate redisTemplate;    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        if (handler instanceof HandlerMethod) {            HandlerMethod hm = (HandlerMethod) handler;            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);            if (null == accessLimit) {                return true;            }            int seconds = accessLimit.seconds();            int maxCount = accessLimit.maxCount();            boolean needLogin = accessLimit.needLogin();            if (needLogin) {                //判断是否登录            }            String ip=request.getRemoteAddr();            String key = request.getServletPath() + ":" + ip ;            Integer count = (Integer) redisTemplate.opsForValue().get(key);            if (null == count || -1 == count) {                redisTemplate.opsForValue().set(key, 1,seconds, TimeUnit.SECONDS);                return true;            }            if (count < maxCount) {                count = count+1;                redisTemplate.opsForValue().set(key, count,0);                return true;            }            //  response 返回 json 请求过于频繁请稍后再试            throw new DujiaoshouException(20001,"操作过于频繁");        }        return true;    }}
  • 在webconfig中配置拦截器
import com.qykhhr.dujiaoshouservice.Interceptor.AccessLimtInterceptor;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/** * 在webconfig中配置拦截器 */@Configurationpublic class MyWebMvcConfigurer extends WebMvcConfigurerAdapter {    @Autowired    private AccessLimtInterceptor accessLimtInterceptor;    @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(accessLimtInterceptor);        super.addInterceptors(registry);    }}
  • 在Controller前面加上注解就可以生效了
@RestControllerpublic class AppHomeController {    @GetMapping("/index")    @AccessLimit(seconds = 1, maxCount = 3) //1秒内 允许请求3次    public R getImageList(){        return R.ok().data("appHome","hahaha");    }}

使用python发送100次请求,可以发现请求被拦截了多少

对于注解,我们也可以不使用它,但是我们需要在拦截器中写入固定的参数。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/124796.html

相关文章

  • SpringBoot+SpringSecurity+jwt整合及初体验

    摘要:进行下一项配置,为了区分必须加入。另起一行,以示尊重。这行代码主要是用于验证,后面再说。然后跑下接口,发现没问题,正常打印,说明主体也在上下文中了。说明这会上下文环境中我们主体不存在。所说以,主体数据生命周期是一次请求。 showImg(https://segmentfault.com/img/bVbtoG1?w=1600&h=900); 原来一直使用shiro做安全框架,配置起来相当...

    dackel 评论0 收藏0
  • 004. 前端跨域资源请求: JSONP/CORS/反向代理

    摘要:同源策略浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源。不受同源策略限制的跨域资源的引入是允许的页面中的链接,重定向以及表单提交是不会受到同源策略限制的。1.什么是跨域资源请求? https://www.cnblogs.com/niuli1987/p/10252214.html 同源: 如果两个页面的协议,端口(如果有指定)和域名都相同,则两个页面具有相...

    番茄西红柿 评论0 收藏0
  • 主机商如何防止攻击-针对互联网攻击,高防服务器将如何防御?

    摘要:针对互联网攻击,高防服务器将如何防御高防服务器只能防下,且防护能力有限,现在都普遍使用云防了,又有加速效果节省源服务器带宽成本,还能防攻击攻击以及各种的页面篡改注入等类型的攻击。游戏服务器被恶意攻击怎么办,如何防御ddos攻击?DDoS,英文Distributed Denial of Service,即分布式拒绝服务。DDoS攻击指借助于客户/服务器技术,将多个计算机联合起来作为攻击平台,对...

    OpenDigg 评论0 收藏0
  • WAF-UWAFWeb安全防护报告

    摘要:部署地域分布客户在业务部署区域的选择上也有不同,从客户业务部署地域分布来看,主要集中在国内的北京和上海,客户通常会选择购买业务部署区域的,也有客户采用多地域部署以提高业务的可用性,总体来看客户的需求集中在防御攻击防攻击以及满足合规需求。2021年UWAF累积为各个行业的客户提供了1117个域名的高质量访问服务,并提供安全防护,有效的保护了客户的数据信息与资产安全。2021年Web安全形势依然...

    ernest.wang 评论0 收藏0

发表评论

0条评论

kel

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<