erdarun
erdarun

Reputation: 551

Spring boot Embedded Tomcat "application/json" post request restriction to 10KB

I'm using Spring boot embedded tomcat for publishing rest service.

Spring boot version used latest "1.3.6.RELEASE"

I have requirement to limit the application/json post request size to 10KB.

Tired this solution but not working, Increase HTTP Post maxPostSize in Spring Boot

Please help.

Thanks, Arun.

Upvotes: 1

Views: 8031

Answers (1)

Andy Wilkinson
Andy Wilkinson

Reputation: 116061

Configuring the max post size only applies to requests with a Content-Type of multipart/form-data or application/x-www-form-urlencoded. There's no mechanism available out of the box in Tomcat to limit the size of a request body for requests with any other content type so you'll have to write some code.

You could limit the content length using a filter. For example, adding the following class to your Spring Boot application will reject an request with a Content-Type that is compatible with application/json and a Content-Length over 10000:

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

}

Note that this filter won't reject requests without a Content-Length header that exceed 10000 bytes, for example one that uses chunked encoding.

Upvotes: 13

Related Questions