Skip to content

MethodBan

MoonSeonghun edited this page Mar 6, 2024 · 4 revisions

@MethodBan

The @MethodBan enables you to implement a simple Rate Limit within your controller.

It basically works based on the IP of the user accessing the API.

Only IP based ban :

@GetMapping("/")
@MethodBan(times = 3, seconds = 10, banSeconds = 1000)
public String hello() {
  return "Hello World!";
}

Once a same IP accesses an API 3 times within 10 seconds, they are prevented from accessing the same API for 1000 banSeconds.

IP & User based ban :

When utilizing public networks, users may experience unexpected blocking. To mitigate this, additionalFilter narrows down the targets of IP-based blocking.

The MethodBan will act on the IP with the argument value of the parameter specified in additionalFilter.

An example of usage is as follows:

@MethodBan(.. additionalFilter = @ParameterFilter(name = "enterpriseUser"))

The @MethodBan annotation will act on the intersection of the IP address and the argument value of the parameter specified in the additionalFilter.

Here's an example usage:

An example usage is as follows

@PostMapping("/")
@MethodBan(times = 3, seconds = 10, banSeconds = 1000,
    banMessage = "You're writing too fast. Please try again later.",
    additionalFilter = @ParameterFilter(name = "enterpriseUser")) // this
public void createJobPosting(
    @CurrentUser EnterpriseUserAccount enterpriseUser) {
  // ... 

}

Note: The toString() or hashCode of the parameter object utilized in ParameterFilter should be uniquely override based on your business requirements.

Customize exception response

@RestControllerAdvice
public class ExceptionHandler {

  @ExceptionHandler(BanException.class)
  public void handleBanException(BanException e) {
  // ... do customize response
    
  }

}
Clone this wiki locally