在tomee中禁用OPTIONS http请求

问题描述 投票:0回答:1

我正在寻找一种方法来禁用我的 java EE 应用程序中的 http 选项请求,安全审计表明我们应该禁用该请求。我正在用curl命令测试它:

curl -i --request-target "*" -X 选项 http://localhost:8080/something/

我总是得到回复:

HTTP/1.1 200 允许:GET、HEAD、POST、PUT、DELETE、OPTIONS 内容长度:0 日期:2024 年 10 月 1 日,星期二 12:21:46 GMT 服务器:Apache TomEE

无论我做什么,总是允许使用相同的方法

我尝试使用自定义标头过滤器删除它,如下所示:

public class OptionsMethodFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            // Handle the OPTIONS request explicitly and prevent default behavior
            response.setHeader("Allow", "GET, POST, PUT, DELETE");
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            // Continue with the regular request handling
            chain.doFilter(req, res);
        }
    }

并且我之前已经在 web.xml 中配置了安全约束

    <security-constraint>
        <display-name>Locked Resources</display-name>
        <web-resource-collection>
            <web-resource-name>securityconstraint</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>PUT</http-method>
            <http-method>DELETE</http-method>
            <http-method>HEAD</http-method>
            <http-method>TRACE</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>authusr</role-name>
        </auth-constraint>
    </security-constraint>
java http-headers apache-tomee
1个回答
0
投票

许多事情都符合“禁用”的条件。也许您可以通过完全禁止 OPTIONS 来进一步回答不包含 OPTIONS 的 OPTIONS 。以下方法是对您提供的过滤器方法的更新。该代码返回 403 - 禁止状态,而不是向选项提供响应,然后停止执行任何其他过滤器。您可以调试它以确保它被调用。

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
        throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    // Check if the method is OPTIONS and send 403 Forbidden
    if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
       // Send 403 Forbidden
        httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //Stop any further processing of the request 
        return;
    }

    // Continue with the next filter in the chain
    chain.doFilter(request, response);
}
© www.soinside.com 2019 - 2024. All rights reserved.