在 Spring Boot 应用程序中禁用 HTTP OPTIONS 方法 [英] Disable HTTP OPTIONS method in spring boot application

查看:72
本文介绍了在 Spring Boot 应用程序中禁用 HTTP OPTIONS 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 spring boot 应用程序上开发了 rest API.API 仅接受 GET 和 POST ,但在使用 OPTIONS 方法请求时,API 会响应 200 状态(而不是 405).我在 google 上搜索了这个问题,但没有一个解决方案是基于 springboot 的.

I had developed rest API on spring boot application. The APIs accept only GET , and POST , but on requesting using OPTIONS method , API responding 200 status (instead of 405). I googled this issue , but none of the solution was springboot based .

回复:

Allow: OPTIONS, TRACE, GET, HEAD, POST
Public: OPTIONS, TRACE, GET, HEAD, POST

需要禁用 OPTIONS 方法.

Need to disable OPTIONS method.

推荐答案

以前的答案 仅适用于 tomcat,因此添加我的也是.例如,您可以通过使用标准 servlet 过滤器来禁用方法跨容器:

Previous answer is for tomcat only, so adding mine as well. You can disable the method cross-container by, for example, using a standard servlet filter:

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.springframework.stereotype.Component;     
import org.springframework.web.filter.OncePerRequestFilter; 

@Component
public class MethodFilter extends OncePerRequestFilter { 

    @Override 
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
                    throws ServletException, IOException { 
        if (request.getMethod().equals("OPTIONS")) {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        } else { 
            filterChain.doFilter(request, response); 
        } 
    }
} 

注意:假设这个类是由 Spring 组件扫描的.如果没有,您可以使用其他注册方法,详见此处.

Note: it is assumed that this class is componentscanned by Spring. If not, you can use other registration methods as detailed in here.

这篇关于在 Spring Boot 应用程序中禁用 HTTP OPTIONS 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆