SoFunction
Updated on 2025-03-03

Solutions to malicious refresh and brute-force requests in SpringBoot interface

In actual project use, the security of the service must be considered. After the service is deployed to the Internet, the service must be considered when it is maliciously requested and brute-force attacked. The following tutorial disables IP through intercept and redis to the number of visits to url+ip within a certain period of time. You can modify it according to your needs to fight your own purpose;

First of all, the project is built for the springboot framework and will not be described in detail.

Directly on the core code.

First create a custom interceptor class, which is also the most core code:

/**
  * @package:
  * @className: IpUrlLimitInterceptor
  * @description: ip+url repeated requests now interceptor
  **/
@Slf4j
public class IpUrlLimitInterceptor implements HandlerInterceptor {
 
 
 private RedisUtil getRedisUtil() {
  return  ();
 }
 
 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 {
  ("requestRequest addressuri={},ip={}", (), (httpServletRequest));
  if (ipIsLock((httpServletRequest))){
   ("ipAccess is prohibited={}",(httpServletRequest));
   ApiResult result = new ApiResult(ResultEnum.LOCK_IP);
   returnJson(httpServletResponse, (result));
   return false;
  }
  if(!addRequestTime((httpServletRequest),())){
   ApiResult result = new ApiResult(ResultEnum.LOCK_IP);
   returnJson(httpServletResponse, (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: Determine whether IP is disabled
   * @param ip
   * @return
   */
 private Boolean ipIsLock(String ip){
  RedisUtil redisUtil=getRedisUtil();
  if((LOCK_IP_URL_KEY+ip)){
   return true;
  }
  return false;
 }
 /**
   * @Description: Record the number of requests
   * @param ip
   * @param uri
   * @return
   */
 private Boolean addRequestTime(String ip,String uri){
  String key=IP_URL_REQ_TIME+ip+uri;
  RedisUtil redisUtil=getRedisUtil();
  if ((key)){
   long time=(key,(long)1);
   if (time>=LIMIT_TIMES){
    (LOCK_IP_URL_KEY+ip,ip,IP_LOCK_TIME);
    return false;
   }
  }else {
   (key,(long)1,1);
  }
  return true;
 }
 
 private void returnJson(HttpServletResponse response, String json) throws Exception {
  PrintWriter writer = null;
  ("UTF-8");
  ("text/json; charset=utf-8");
  try {
   writer = ();
   (json);
  } catch (IOException e) {
   ("LoginInterceptor response error ---> {}", (), e);
  } finally {
   if (writer != null) {
    ();
   }
  }
 }
 
 
}

Redis in the code uses the form of distributed locks, which can ensure thread safety and functional implementation to the greatest extent. The code sets that the same interface in 1S is accessed 5 times through the same IP, and the IP is disabled for 1 hour. According to your project needs, you can modify it appropriately to realize the functions you want;

Key code of redis distributed lock:

/**
 * @package: 
 * @className: RedisUtil
 **/
@Component
@Slf4j
public class RedisUtil {
 
 private static final Long SUCCESS = 1L;
 
 @Autowired
 private RedisTemplate<String, Object> redisTemplate;
 // =============================common============================
 
 
 
 /**
   * Acquire the lock
   * @param lockKey
   * @param value
   * @param expireTime: Units - seconds
   * @return
   */
 public boolean getLock(String lockKey, Object value, int expireTime) {
  try {
   ("Add a distributed lockkey={},expireTime={}",lockKey,expireTime);
   String script = "if ('setNx',KEYS[1],ARGV[1]) then if ('get',KEYS[1])==ARGV[1] then return ('expire',KEYS[1],ARGV[2]) else return 0 end end";
   RedisScript<String> redisScript = new DefaultRedisScript<>(script, );
   Object result = (redisScript, (lockKey), value, expireTime);
   if ((result)) {
    return true;
   }
  } catch (Exception e) {
   ();
  }
  return false;
 }
 
 /**
   * Release the lock
   * @param lockKey
   * @param value
   * @return
   */
 public boolean releaseLock(String lockKey, String value) {
  String script = "if ('get', KEYS[1]) == ARGV[1] then return ('del', KEYS[1]) else return 0 end";
  RedisScript<String> redisScript = new DefaultRedisScript<>(script, );
  Object result = (redisScript, (lockKey), value);
  if ((result)) {
   return true;
  }
  return false;
 }
 
}

Finally, pass the above custom interceptorAdd it and it will take effect;

@Configuration
@Slf4j
public class MyWebAppConfig extends WebMvcConfigurerAdapter {
    @Bean
 IpUrlLimitInterceptor getIpUrlLimitInterceptor(){
     return new IpUrlLimitInterceptor();
 }
 
 @Override
    public void addInterceptors(InterceptorRegistry registry) {
  (getIpUrlLimitInterceptor()).addPathPatterns("/**");
        (registry);
    }
}

This is the article about the solution to malicious refresh and brute force requests of SpringBoot interface. For more related contents of malicious refresh and brute force requests of SpringBoot interface, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!