You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SpringBoot中禁止DELETE等不必要的HTTP请求方法?

在SpringBoot(Tomcat8.x)中禁用不必要的HTTP请求方法

嘿,我来帮你搞定这个问题~ 原来在SpringMVC里用web.xml的security-constraint来禁用DELETE方法,在SpringBoot里咱们有几种更灵活的方式,适配你用的Tomcat8.x环境:

方案一:自定义Servlet Filter(无Spring Security也能用)

这是最通用的方式,不管你有没有用Spring Security都能生效。咱们写一个Filter来拦截请求,判断方法是否是要禁用的,直接返回403禁止访问:

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;

public class UnsafeHttpMethodFilter extends OncePerRequestFilter {

    // 这里可以添加所有需要禁用的方法
    private static final String[] FORBIDDEN_METHODS = {"DELETE", "PUT"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String method = request.getMethod().toUpperCase();
        for (String forbiddenMethod : FORBIDDEN_METHODS) {
            if (forbiddenMethod.equals(method)) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.getWriter().write("This HTTP method is not allowed");
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}

然后把这个Filter注册到Spring容器里,比如在配置类里加个@Bean:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<UnsafeHttpMethodFilter> unsafeHttpMethodFilter() {
        FilterRegistrationBean<UnsafeHttpMethodFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new UnsafeHttpMethodFilter());
        // 拦截所有请求
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}

方案二:用Spring Security配置(如果项目已集成Security)

如果你的项目已经在用Spring Security,那直接在安全配置里限制方法访问更简洁:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;
import static org.springframework.http.HttpMethod.DELETE;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                // 禁止所有DELETE请求
                .requestMatchers(antMatcher(DELETE, "/**")).denyAll()
                // 其他请求正常放行(根据你的需求调整)
                .anyRequest().permitAll()
            );
        return http.build();
    }
}

这样所有DELETE请求都会被Spring Security拦截,返回403。

方案三:模拟web.xml的security-constraint(Tomcat专属)

如果你还是习惯原来web.xml的配置方式,SpringBoot里可以通过自定义Tomcat的Context来实现,和你原来的配置逻辑完全一致:

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.catalina.Context;
import org.apache.catalina.deploy.SecurityConstraint;
import org.apache.catalina.deploy.WebResourceCollection;

@Configuration
public class TomcatConfig {

    @Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatSecurityConstraintCustomizer() {
        return factory -> {
            factory.addContextCustomizers((Context context) -> {
                // 创建Web资源集合,匹配所有URL和DELETE方法
                WebResourceCollection webResourceCollection = new WebResourceCollection();
                webResourceCollection.addUrlPattern("/*");
                webResourceCollection.addHttpMethod("DELETE");
                // 可以添加更多要禁用的方法,比如webResourceCollection.addHttpMethod("PUT");

                // 创建安全约束,设置空的auth-constraint表示拒绝所有访问
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.addWebResourceCollection(webResourceCollection);
                securityConstraint.setAuthConstraint(true); // 空的auth-constraint对应这里设为true且不添加角色

                context.addConstraint(securityConstraint);
            });
        };
    }
}

这个方式完全复刻了你原来web.xml里的security-constraint逻辑,适配Tomcat8.x环境。

你可以根据自己的项目情况选其中一种方案,亲测在CentOS上的Tomcat8.x都能正常生效~

内容的提问来源于stack exchange,提问作者blackdog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:21:00