SoFunction
Updated on 2025-03-08

Two ways to implement the interface of SpringBoot to prevent brushing

What is interface anti-brush

Interfaces are flashed refer to the frequent call of the same interface, which may be caused by the following reasons:

  • Malicious attack:Attackers use automated scripts or tools to make large amounts of requests to the interface to consume system resources, slow down system responses, or achieve other malicious purposes.
  • Misoperation or program error:In some cases, program errors or misoperation may cause the interface to be repeatedly called, such as loop calls or timing task configuration errors.

Common interface anti-brushing strategies

  1. Request frequency limit: limits the number of times a single user or IP address can send requests within a certain period of time, and prevents users from sending requests excessively frequently.

  2. Verification code verification: The user requires verification code verification before sending the request, thus ensuring that the request is from the real user rather than the robot.

  3. User Identity Authentication: requires users to authenticate before sending a request, such as logging in with a username and password or using an API key to authenticate, ensuring that only legitimate users can send the request.

  4. Dynamic token: Generate a dynamic token for each request, requiring the client to attach the token in the request, and the server side verifies the legitimacy of the request based on the token.

  5. Abnormal behavior detection: detect abnormal request behavior by monitoring the user's behavior and request patterns, such as sending a large number of requests or sending duplicate requests in a short time, thereby identifying and blocking malicious users or robots.

Redis implements interface flash protection

Redis is a high-performance key-value storage system, which is often used in scenarios such as cache and distributed locks. Redis can effectively implement the interface brushing function:

  • counter:Using Redis's counter function, the counter value is increased each time the interface is called, and the maximum number of calls in a time window is set. If the number of times exceeds this, the request will be rejected.
  • Distributed lock:Use Redis's distributed locking function to ensure that only one request can increase the counter value at the same time, preventing concurrency problems from causing the counter to fail.

Code Example

import ;
import ;
import ;
import ;
import ;

import ;

@Component
public class RateLimitInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ipAddress = ();
        String key = "rate_limit:" + ipAddress;
        long count = ().increment(key, 1);
        if (count == 1) {
            (key, 1, ); // Set expiration time to prevent permanent storage of data        }
        if (count > 100) { // Set the threshold to a maximum of 100 requests per minute            (HttpStatus.TOO_MANY_REQUESTS.value());
            ().write("Requests are too frequent, please try again later");
            return false;
        }
        return true;
    }
}

Interceptor implements interface brush protection

  • Writing an interceptor: Create an interceptor class that implements the HandlerInterceptor interface, override the preHandle method, check the number of interface calls in this method, and intercept the request if the threshold is exceeded.
  • Configure the interceptor: In the Spring Boot configuration class, register the interceptor into the interceptor chain through the addInterceptor method, and configure the interceptor path and exclusion path of the interceptor.

Code Example

Use interceptor to achieve interface brush protection

import ;
import ;
import ;
import ;

@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    private static final int MAX_REQUESTS_PER_MINUTE = 100;
    private static final String RATE_LIMIT_KEY_PREFIX = "rate_limit:";
    private final RedisTemplate<String, String> redisTemplate;

    public RateLimitInterceptor(RedisTemplate<String, String> redisTemplate) {
         = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ipAddress = ();
        String key = RATE_LIMIT_KEY_PREFIX + ipAddress;
        Long count = ().increment(key, 1);
        if (count == 1) {
            (key, 1, );
        }
        if (count > MAX_REQUESTS_PER_MINUTE) {
            (HttpStatus.TOO_MANY_REQUESTS.value());
            ().write("Requests are too frequent, please try again later");
            return false;
        }
        return true;
    }
}

Interceptor configuration

import ;
import ;
import ;

import ;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final RateLimitInterceptor rateLimitInterceptor;

    @Autowired
    public WebMvcConfig(RateLimitInterceptor rateLimitInterceptor) {
         = rateLimitInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        (rateLimitInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/exclude/**"); // You can exclude some paths that do not require interception    }
}

Summarize

Interface anti-brushing is an important means to ensure the safety and stability of the system. Redis and interceptors can achieve the interface anti-brushing function well. By reasonably setting thresholds and time windows and monitoring system logs, abnormal situations can be discovered in a timely manner and corresponding measures can be taken to ensure the normal operation of the system

The above is the detailed content of two methods of SpringBoot to implement interface anti-brushing. For more information about SpringBoot interface anti-brushing, please pay attention to my other related articles!