Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit size of http application/json request body in Spring, tomcat

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.

like image 598
Fredster Avatar asked Sep 08 '17 14:09

Fredster


1 Answers

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))));
    }
}
like image 67
Hardik Uchdadiya Avatar answered Sep 30 '22 17:09

Hardik Uchdadiya