13

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.

Fredster
  • 146
  • 1
  • 1
  • 7
  • 5
    In my opinion the refereced question does not answer this question. There is no default limit. I tried requests with roughly 20 MB and they were accepted. I also configured the server.tomcat.max-http-post-size property from spring - and it did not work. Though I can try configuring it directly in the tomcat settings – Fredster Sep 08 '17 at 16:45

2 Answers2

2

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))));
    }
}
0

you can try this for post requests in spring boot :

server.tomcat.max-http-form-post-size
  • 3
    `max-http-form-post-size` is the Spring Boot 2.x equivalent of `max-http-post-size` (which didn't work for the OP). The property was renamed to stress out that it **only** applies to content of type `application/x-www-form-urlencoded`. – Piotr P. Karwasz Aug 24 '21 at 09:30