【问题标题】:Limit size of http application/json request body in Spring, tomcatSpring,tomcat中http应用程序/json请求体的限制大小
【发布时间】:2018-02-17 12:10:06
【问题描述】:

我想限制接受的应用程序/json http 请求正文的大小。这样就不可能向我的应用程序发送数兆字节的 json,然后对其进行处理并使我的应用程序运行很长时间。

我在这里读到过,没有现成的解决方案可以做到这一点。 Spring boot Embedded Tomcat "application/json" post request restriction to 10KB

除了自己实现某些东西之外,还有其他解决方案吗? 对我来说,这似乎是一个非常常见的用例,我不敢相信没有通用的解决方案,因为这是一个非常容易被利用的安全问题。

【问题讨论】:

  • 在我看来,引用的问题没有回答这个问题。没有默认限制。我尝试了大约 20 MB 的请求,它们被接受了。我还从 spring 配置了 server.tomcat.max-http-post-size 属性 - 它没有工作。虽然我可以尝试直接在 tomcat 设置中配置它

标签: java json spring http tomcat


【解决方案1】:

你可以在 spring boot 中尝试这个发布请求:

server.tomcat.max-http-form-post-size

【讨论】:

  • max-http-form-post-sizemax-http-post-size 的 Spring Boot 2.x 等效项(不适用于 OP)。该属性已重命名以强调它适用于 application/x-www-form-urlencoded 类型的内容。
【解决方案2】:

没有开箱即用的解决方案,但最简单的方法是编写一个过滤器来检查请求长度,就像这样

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

【讨论】:

    猜你喜欢
    • 2016-02-21
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 2021-12-26
    • 1970-01-01
    • 2021-07-06
    • 2018-01-09
    相关资源
    最近更新 更多