在Spring Boot中禁止使用OPTIONS请求

时间:2018-12-30 09:08:08

标签: spring spring-boot cors preflight

我阅读了很多有关此问题的线程和解决方案(包括this SO solution),但是在发送预检请求时仍然出现403错误。

我正在使用Spring Data Rest,只要没有发送任何OPTIONS,我就可以很好地与我的存储库一起工作。我还没有使用Spring Security,但是我打算尽快配置它。这是我当前的配置:

@Configuration
public class GlobalRepositoryRestConfigurer extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.getCorsRegistry().addMapping("/**").allowedOrigins("*").allowedHeaders(
                "*").exposedHeaders("Location").allowedMethods("GET", "PUT", "POST", "DELETE",
                                                               "OPTIONS");
    }

    @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
    public DispatcherServlet dispatcherServlet() {
        DispatcherServlet dispatcher = new DispatcherServlet();
        dispatcher.setDispatchOptionsRequest(true);
        return dispatcher;
    }
}

我也尝试了application.properties选项,并将allowedMethods设置为"*",但是无论如何我最终都得到了403。以下是我从OPTIONS请求中获得的请求/响应标头。

请求标头

Accept           text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding  gzip, deflate
Accept-Language  fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Access-Control-Request-Headers   content-type
Access-Control-Request-Method    POST
Connection       keep-alive
Host             localhost:8080
Origin           http://localhost:4000
Referer          http://localhost:4000/
User-Agent       Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/64.0

响应头

Allow            GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH
Content-Length   20
Date             Sun, 30 Dec 2018 08:49:00 GMT

您是否看到任何错误或我可以尝试的其他方法?

1 个答案:

答案 0 :(得分:0)

我仍然不知道为什么我的配置不能用于OPTIONS请求,但是我设法使其与WebMvcConfigurer一起使用。这是解决我的问题的配置类:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .exposedHeaders("Location", "Access-Control-Allow-Origin");
    }
}