I want to limit the size of accepted application/json http request bodys. So that it is not possible to send multiple megabytes of json to my application, which are then processed and make my app run for a long time.
I've read here that there is no out of the box solution to do this. Spring boot Embedded Tomcat "application/json" post request restriction to 10KB
Is there another solution beside implementing something myself. For me this seems like a very common use-case and I can't believe that there is no general solution for this, because this is a very easily exploitable security issue.
there is no out of the box solution, but simplest way would be to write a filter to check request length, something like this
@Component
static class ApplicationJsonRequestSizeLimitFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (isApplicationJson(request) && request.getContentLengthLong() > 10000) {
throw new IOException("Request content exceeded limit of 10000 bytes");
}
filterChain.doFilter(request, response);
}
private boolean isApplicationJson(HttpServletRequest httpRequest) {
return (MediaType.APPLICATION_JSON.isCompatibleWith(MediaType
.parseMediaType(httpRequest.getHeader(HttpHeaders.CONTENT_TYPE))));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With