首页 > 其他分享 >几行代码,搞定 SpringBoot 接口恶意刷新和暴力请求!

几行代码,搞定 SpringBoot 接口恶意刷新和暴力请求!

时间:2022-10-13 21:32:23浏览次数:52  
标签:httpServletRequest 搞定 return SpringBoot ip 几行 private IP String

几行代码,搞定 SpringBoot 接口恶意刷新和暴力请求!_ipad

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

首先工程为springboot框架搭建,不再详细叙述。

直接上核心代码。

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

/**
* @package: com.technicalinterest.group.interceptor
* @className: IpUrlLimitInterceptor
* @description: ip+url重复请求现在拦截器
* @author: Shuyu.Wang
* @since: 0.1
**/
@Slf4j
public class IpUrlLimitInterceptor implements HandlerInterceptor {


private RedisUtil getRedisUtil(){
return SpringContextUtil.getBean(RedisUtil.class);
}

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 int IP_LOCK_TIME=60;

@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
log.info("request请求地址uri={},ip={}", httpServletRequest.getRequestURI(), IpAdrressUtil.getIpAdrress(httpServletRequest));
if (ipIsLock(IpAdrressUtil.getIpAdrress(httpServletRequest))){
log.info("ip访问被禁止={}",IpAdrressUtil.getIpAdrress(httpServletRequest));
ApiResult result = new ApiResult(ResultEnum.LOCK_IP);
returnJson(httpServletResponse, JSON.toJSONString(result));
return false;
}
if(!addRequestTime(IpAdrressUtil.getIpAdrress(httpServletRequest),httpServletRequest.getRequestURI())){
ApiResult result = new ApiResult(ResultEnum.LOCK_IP);
returnJson(httpServletResponse, JSON.toJSONString(result));
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 {

}

/**
* @Description: 判断ip是否被禁用
* @author: shuyu.wang
* @date: 2019-10-12 13:08
* @param ip
* @return java.lang.Boolean
*/
private Boolean ipIsLock(String ip){
RedisUtil redisUtil=getRedisUtil();
if(redisUtil.hasKey(LOCK_IP_URL_KEY+ip)){
return true;
}
return false;
}
/**
* @Description: 记录请求次数
* @author: shuyu.wang
* @date: 2019-10-12 17:18
* @param ip
* @param uri
* @return java.lang.Boolean
*/
private Boolean addRequestTime(String ip,String uri){
String key=IP_URL_REQ_TIME+ip+uri;
RedisUtil redisUtil=getRedisUtil();
if (redisUtil.hasKey(key)){
long time=redisUtil.incr(key,(long)1);
if (time>=LIMIT_TIMES){
redisUtil.getLock(LOCK_IP_URL_KEY+ip,ip,IP_LOCK_TIME);
return false;
}
}else {
redisUtil.getLock(key,(long)1,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禁用1个小时,根据自己项目需求可以自己适当修改,实现自己想要的功能;

redis分布式锁的关键代码:

/**
* @package: com.shuyu.blog.util
* @className: RedisUtil
* @description:
* @author: Shuyu.Wang
* @since: 0.1
**/
@Component
@Slf4j
public class RedisUtil {

private static final Long SUCCESS = 1L;

@Autowired
private RedisTemplate<String, Object> redisTemplate;
// =============================common============================



/**
* 获取锁
* @param lockKey
* @param value
* @param expireTime:单位-秒
* @return
*/
public boolean getLock(String lockKey, Object value, int expireTime){
try {
log.info("添加分布式锁key={},expireTime={}",lockKey,expireTime);
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<String> redisScript = new DefaultRedisScript<>(script, String.class);
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime);
if (SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

/**
* 释放锁
* @param lockKey
* @param value
* @return
*/
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<String> redisScript = new DefaultRedisScript<>(script, String.class);
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value);
if (SUCCESS.equals(result)) {
return true;
}
return false;
}

}

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

@Configuration
@Slf4j
public class MyWebAppConfig extends WebMvcConfigurerAdapter {
@Bean
IpUrlLimitInterceptor getIpUrlLimitInterceptor(){
return new IpUrlLimitInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(getIpUrlLimitInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}

自己可以写一个for循环来测试方面的功能,这里就不详细介绍了。

标签:httpServletRequest,搞定,return,SpringBoot,ip,几行,private,IP,String
From: https://blog.51cto.com/u_15430445/5754671

相关文章

  • 教你优雅的实现 SpringBoot 并行任务
    SpringBoot的定时任务:第一种:把参数配置到.properties文件中:代码:packagecom.accord.task;importjava.text.SimpleDateFormat;importjava.util.Date;importorg.spring......
  • SpringBoot深入理解
    当使用打包时,会下载org-springframework-boot-loader的jar,并且不会放在lib存放的第三方jar包文件中,该jar包中有个JarLauncher.class文件中设置了jar包运行时的入口和打包后......
  • 计算机毕业设计基于SpringBoot兼职招聘系统
    ......
  • 通过dockerfile发布微服务Springboot部署到docker容器
    通过IDEA创建一个demo项目新建一个测试接口,并打包成demo.jar,端口为1013通过jar包启动,访问测试接口:http://localhost:1013/hello查看jar包测试结果:{"msg":"测试接口成......
  • springboot整合feign的接口抽离
    前言现在很多微服务框架使用feign来进行服务间的调用,需要在服务端和消费端两边分别对接口和请求返回实体进行编码,维护起来也比较麻烦。那有木有一种可能,只用服务端编......
  • 7天进阶为讲师 | Day 6-搞定培训上下游、全流程
    经过前两节课我们初步掌握了讲师的基本技能,后面三节课又掌握了给客户培训讲解、面向大众进行演讲、使用新媒体方式进行直播和录播,而作为讲师我们还要掌握和讲师相关的一些事......
  • springboot使用自定义注解实现加解密及脱敏
    原文链接: https://www.yisu.com/zixun/622633.html这篇文章主要介绍springboot中如何使用自定义注解实现加解密及脱敏方式,文中介绍的非常详细,具有一定的参考价值,感兴趣......
  • 7天进阶为讲师 | Day 5-搞定新媒体直播和录播
    之前我们已经介绍了内部讲师、面向客户进行讲解、在外部大会上进行演讲,现在越来越多的讲师在新媒体平台中进行直播、录制课程,之前准备PPT是讲师的必备技能之一,而现在来看通......
  • 慕课网--springboot学习项目推荐
    ​​Springboot微信小程序–微信登录功能实战​​​​SpringBoot构建电商基础秒杀项目​​​​SpringBoot+MyBatis搭建迷你小程序​​​​Springboot+ElasticSearch构......
  • springboot配置多数据源mysql,presto,hive等
    下面案例是配置多数据源,两个及以上,但是主数据源只能是一个,默认mybatis使用的是主数据源下面配置mysql为主数据源,通过注解@Primary标注yaml文件配置:spring:datasource......