java - java spring 不会忽略 DELETE 之前发出的 OPTIONS 请求,这与 POST、GET 不同

标签 java spring http

我有一个 spring 后端,它忽略 OPTIONS 请求方法:

@Override
public void configure(WebSecurity web)
        throws Exception {
    web.ignoring()
        .antMatchers("/api/auth/**");
    web.ignoring()
        .antMatchers(HttpMethod.OPTIONS, "/**");
} 

它适用于 GET 和 POST 请求(即,由于接收初始 OPTIONS 请求,它不会返回 403 Forbidden 响应):

  const request = axios({
    url: deleteEndpoint,
    method: 'POST',
    headers: {
      'Authorization': localStorage.getItem('jwt_token'),
      'Content-Type': 'application/json'
    }
  }); // [1]

当我将方法更改为 DELETE 时:

  const request = axios({
    url: deleteEndpoint,
    method: 'DELETE',
    headers: {
      'Authorization': localStorage.getItem('jwt_token'),
      'Content-Type': 'application/json'
    }
  });

我收到此错误:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 403.

我将 OPTIONS 请求的 web.ignoring 添加到我的网络安全配置中,以免收到此错误消息,并且它适用于除 DELETE 之外的所有请求。

为什么会发生这种情况?为什么在 DELETE 请求之前发出的 OPTIONS 请求不会被忽略,但在 POST 和 GET 之前发出的 OPTIONS 请求会被忽略?

更新 1 我有一个自定义 CORS 策略,如下所示:

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .exposedHeaders("Authorization", "Content-Type");
}

[1] 正如您可以猜到的,这个“实际上”失败了,因为我不希望对删除端点进行 POST 调用,重要的是它到达 REST 端点并失败,因为具有预期的有效负载。

最佳答案

添加新的全局 cors 政策。默认情况下,允许所有来源以及 GET、HEAD 和 POST 方法。示例:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://domain2.com")
            .allowedMethods("PUT", "DELETE")
                .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(false).maxAge(3600);
    }

}

引用https://spring.io/blog/2015/06/08/cors-support-in-spring-framework了解更多详情

关于java - java spring 不会忽略 DELETE 之前发出的 OPTIONS 请求,这与 POST、GET 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48335616/

相关文章:

java - Hibernate @OneToMany/@ManyToOne 列未出现

java - JComboBox 事件 - Swing

java - Eclipse Spring Boot 构建路径包含重复条目

java - Spring 数据JPA : Find all by example and page and return DTO (Projection)

ruby - 在 Eventmachine 中响应 HTTP 请求

java - 将 JSON 文件注入(inject) map

java - LinkedHashMap 中 'accessOrder' 字段的用途是什么?

java - 我如何使用 Spring 的 RestTemplate 执行与此 curl 命令等效的操作?

html - 发布请求以包含 'Content-Type' 和 JSON

c# - 作为代理或重定向器的负载平衡器