SpringBoot 接口恶意刷新和暴力请求

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

首先工程为springboot框架搭建,不再详细叙述。直接上核心代码。

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

  1. /**
  2. * @package: com.technicalinterest.group.interceptor
  3. * @className: IpUrlLimitInterceptor
  4. * @description: ip+url重复请求现在拦截器
  5. * @author: Shuyu.Wang
  6. * @date: 2019-10-12 12:34
  7. * @since: 0.1
  8. **/
  9. @Slf4j
  10. public class IpUrlLimitInterceptor implements HandlerInterceptor {
  11. private RedisUtil getRedisUtil() {
  12. return SpringContextUtil.getBean(RedisUtil.class);
  13. }
  14. private static final String LOCK_IP_URL_KEY="lock_ip_";
  15. private static final String IP_URL_REQ_TIME="ip_url_times_";
  16. private static final long LIMIT_TIMES=5;
  17. private static final int IP_LOCK_TIME=60;
  18. @Override
  19. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
  20. log.info("request请求地址uri={},ip={}", httpServletRequest.getRequestURI(), IpAdrressUtil.getIpAdrress(httpServletRequest));
  21. if (ipIsLock(IpAdrressUtil.getIpAdrress(httpServletRequest))){
  22. log.info("ip访问被禁止={}",IpAdrressUtil.getIpAdrress(httpServletRequest));
  23. ApiResult result = new ApiResult(ResultEnum.LOCK_IP);
  24. returnJson(httpServletResponse, JSON.toJSONString(result));
  25. return false;
  26. }
  27. if(!addRequestTime(IpAdrressUtil.getIpAdrress(httpServletRequest),httpServletRequest.getRequestURI())){
  28. ApiResult result = new ApiResult(ResultEnum.LOCK_IP);
  29. returnJson(httpServletResponse, JSON.toJSONString(result));
  30. return false;
  31. }
  32. return true;
  33. }
  34. @Override
  35. public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  36. }
  37. @Override
  38. public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  39. }
  40. /**
  41. * @Description: 判断ip是否被禁用
  42. * @author: shuyu.wang
  43. * @date: 2019-10-12 13:08
  44. * @param ip
  45. * @return java.lang.Boolean
  46. */
  47. private Boolean ipIsLock(String ip){
  48. RedisUtil redisUtil=getRedisUtil();
  49. if(redisUtil.hasKey(LOCK_IP_URL_KEY+ip)){
  50. return true;
  51. }
  52. return false;
  53. }
  54. /**
  55. * @Description: 记录请求次数
  56. * @author: shuyu.wang
  57. * @date: 2019-10-12 17:18
  58. * @param ip
  59. * @param uri
  60. * @return java.lang.Boolean
  61. */
  62. private Boolean addRequestTime(String ip,String uri){
  63. String key=IP_URL_REQ_TIME+ip+uri;
  64. RedisUtil redisUtil=getRedisUtil();
  65. if (redisUtil.hasKey(key)){
  66. long time=redisUtil.incr(key,(long)1);
  67. if (time>=LIMIT_TIMES){
  68. redisUtil.getLock(LOCK_IP_URL_KEY+ip,ip,IP_LOCK_TIME);
  69. return false;
  70. }
  71. }else {
  72. redisUtil.getLock(key,(long)1,1);
  73. }
  74. return true;
  75. }
  76. private void returnJson(HttpServletResponse response, String json) throws Exception {
  77. PrintWriter writer = null;
  78. response.setCharacterEncoding("UTF-8");
  79. response.setContentType("text/json; charset=utf-8");
  80. try {
  81. writer = response.getWriter();
  82. writer.print(json);
  83. } catch (IOException e) {
  84. log.error("LoginInterceptor response error ---> {}", e.getMessage(), e);
  85. } finally {
  86. if (writer != null) {
  87. writer.close();
  88. }
  89. }
  90. }
  91. }

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

redis分布式锁的关键代码:

  1. /**
  2. * @package: com.shuyu.blog.util
  3. * @className: RedisUtil
  4. * @description:
  5. * @author: Shuyu.Wang
  6. * @date: 2019-07-14 14:42
  7. * @since: 0.1
  8. **/
  9. @Component
  10. @Slf4j
  11. public class RedisUtil {
  12. private static final Long SUCCESS = 1L;
  13. @Autowired
  14. private RedisTemplate<String, Object> redisTemplate;
  15. // =============================common============================
  16. /**
  17. * 获取锁
  18. * @param lockKey
  19. * @param value
  20. * @param expireTime:单位-秒
  21. * @return
  22. */
  23. public boolean getLock(String lockKey, Object value, int expireTime) {
  24. try {
  25. log.info("添加分布式锁key={},expireTime={}",lockKey,expireTime);
  26. 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";
  27. RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
  28. Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime);
  29. if (SUCCESS.equals(result)) {
  30. return true;
  31. }
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. return false;
  36. }
  37. /**
  38. * 释放锁
  39. * @param lockKey
  40. * @param value
  41. * @return
  42. */
  43. public boolean releaseLock(String lockKey, String value) {
  44. String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
  45. RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
  46. Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value);
  47. if (SUCCESS.equals(result)) {
  48. return true;
  49. }
  50. return false;
  51. }
  52. }

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

  1. @Configuration
  2. @Slf4j
  3. public class MyWebAppConfig extends WebMvcConfigurerAdapter {
  4. @Bean
  5. IpUrlLimitInterceptor getIpUrlLimitInterceptor(){
  6. return new IpUrlLimitInterceptor();
  7. }
  8. @Override
  9. public void addInterceptors(InterceptorRegistry registry) {
  10. registry.addInterceptor(getIpUrlLimitInterceptor()).addPathPatterns("/**");
  11. super.addInterceptors(registry);
  12. }
  13. }

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

来源:https://blog.csdn.net/wang_shuyu/article/details/102531940
posted @ 2022-09-25 23:29  程序员小明1024  阅读(49)  评论(0编辑  收藏  举报