spring - 如何在 Spring Boot 中禁止 `DELETE` http 请求?

标签 spring spring-boot tomcat

如果我们不需要在我们的应用程序中使用它,安全部门要求我们禁止DELETE 和其他一些http 请求方法。在 SpringMVC 中,我可以像这样在 web.xml 中添加 security-constraint:

<security-constraint>  
<display-name>delete-method</display-name>  
<web-resource-collection>  
    <web-resource-name>unsafe-method</web-resource-name>  
    <url-pattern>/*</url-pattern>
    <http-method>DELETE</http-method>
</web-resource-collection>  
<auth-constraint/>  

但是我不知道如何在Springboot中添加。服务器是 tomcat8.x 并在 CentOS 上运行。

最佳答案

您可以使用 CORS 过滤器。您可以在那里指定允许的 HTTP 请求类型。

示例来自 the Spring docs :

<mvc:cors>

    <mvc:mapping path="/api/**"
        allowed-origins="http://domain1.com, http://domain2.com"
        allowed-methods="GET, PUT"
        allowed-headers="header1, header2, header3"
        exposed-headers="header1, header2" allow-credentials="false"
        max-age="123" />

    <mvc:mapping path="/resources/**"
        allowed-origins="http://domain1.com" />

</mvc:cors>

您可以使用 Java 来完成。

这是 nice implementation

@Component
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");
        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

关于spring - 如何在 Spring Boot 中禁止 `DELETE` http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50391483/

相关文章:

java - 在 Spring Boot 中重新创建查询

java - 如果 session 过期,如何重定向到登录页面?

java - 在上下文 Tomcat 7 上启用自动部署

spring - @Secured 在 Controller 中不起作用,但拦截 URL 似乎工作正常

java - 如何在 JPQL 中使用别名

spring-boot - 如何将现有用户角色映射到 keycloak 中的自定义用户存储提供程序?

java - 运行时发生异常。空 : InvocationTargetException: Connector configured to listen on port 8080 failed to start -> [Help 1]

java - Tomcat 类加载器不工作

java - Spring DI 的线程安全影响

java - Spring boot 和 maven exec 插件问题