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

后端 未结 1 854
情话喂你
情话喂你 2020-12-20 05:52

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 applica

相关标签:
1条回答
  • 2020-12-20 06:35

    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.

    0 讨论(0)
提交回复
热议问题