选项上的Spring MVC CORS标头,但不允许请求

时间:2018-09-14 01:34:55

标签: spring-mvc tomcat spring-security cors axios

我的代码遇到CORS错误时遇到了问题。如果我从带有--disable-web-security的Chrome实例中运行该代码,则该代码有效。 我的Spring ApplicationConfig中有以下代码:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
        }
    };
}

当我的前端提交其OPTIONS请求时,状态为200的请求成功,并且响应具有以下标头:

 Request URL: http://127.0.0.1:9000/oe/Auth/login
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 127.0.0.1:9000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT, PATCH
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 3600
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Fri, 14 Sep 2018 01:27:15 GMT
Expires: 0
Pragma: no-cache
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

当它随后提交POST登录时,出现以下控制台错误:

Failed to load http://127.0.0.1:9000/oe/Auth/login: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access.

这是“网络”标签

Request URL: http://127.0.0.1:9000/oe/Auth/login
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.1:9000
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Date: Mon, 17 Sep 2018 20:19:48 GMT
Expires: 0
Pragma: no-cache
Server: Apache-Coyote/1.1
Set-Cookie: SESSION=ZjlhYTE5NmMtNDk3NC00Yzc4LTk1MDYtN2FjNzBhMjFhMGI0; Path=/oe/; HttpOnly
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

这是因为Spring Security在我的CorsRegistration发生问题之前抢了这个请求吗?

1 个答案:

答案 0 :(得分:0)

在下面的帖子中,一位朋友推荐我回答一个嵌套在下方的答案。您确实需要针对cors的Spring Security做额外的工作: https://stackoverflow.com/a/43559288/3459721