Question
Limiting the size of a RequestBody
I have following controller. Which takes a post request and process as required.
@RestController
@RequestMapping("/login")
public class LoginController {
@RequestMapping(method = RequestMethod.POST)
public String login(@RequestBody LoginRequest loginRequest) {
if (loginRequest.getUsername().length() < 5 || loginRequest.getUsername().length() > 10) {
return "Username must be between 5 to 10 character.";
}
...
return "This is the login response.";
}
}
LoginRequest.java
public class LoginRequest {
private String username;
private String password;
public LoginRequest() {
}
public LoginRequest(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return this.username;
}
...
}
As seen above, the parameter are passed as HTTP request body @RequestBody LoginRequest loginRequest
The issue is currently, someone can send malicious requests with random large amount of data. For e.g. a username
of 5000 characters. Though the authentication would fail but still multiple such request can impact the performance of the server, and makes it vulnerable to DoS attacks.
Hence, I want to enforce a size validation on application level over the incoming request body. E.g. it shouldn’t be more than 10mb etc. However, I am not sure, how to do it.
A similar question is here, however i am not using jboss and also changing server configurations isnt an option and looking to limit or resolve it on application level. Also, my request isnt a form multipart but rather JSON sent as request body.