为什么我的'Access-Control-Allow-Credentials'不再被发送以响应Spring Boot 2.0.x(在我的情况下为2.0.1.RELEASE)下的预检调用(OPTIONS)?这是我的全局CORS配置在Spring Boot 1.5.6下正常工作:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(
"http://localhost:3000",..)
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
}
};
}}
我的pom依赖项(我正在做自己的安全性并避免Spring Security):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
我对REST endpoints 的服务调用未通过预检:
无法加载http:// localhost:8080 / api / v5 / sec / auth:对预检请求的响应未通过访问控制检查:响应中的“Access-Control-Allow-Credentials”标头的值为''当请求的凭据模式为'include'时,它必须为'true' . 因此不允许来源'http:// localhost:3000'访问 .
我已经验证了在Spring Boot 1.5.6的情况下确实存在'Access-Control-Allow-Credentials' Headers ,并且在Spring Boot 2.0.1下缺少 .
我可以找到的所有文档,包括spring.io here上的最新文档,表示我的全局配置仍然正确,即使WebMvcConfigurerAdapter现在似乎已被弃用 .
UPDATE:
以下是迁移前后的响应标头:
迁移之前(Spring Boot 1.5.6):
Access-Control-Allow-Credentials:true Access-Control-Allow-Origin:http:// localhost:3000 Content-Type:application / json; charset = UTF-8 Date:day,dd Mon yyyy hh:mm:ss GMT Transfer-Encoding:chunked Vary:Origin
迁移后(Spring Boot 2.0.1 - Access-Control-Allow-Credentials标头丢失,但其他人更改/添加):
Access-Control-Allow-Headers:content-type Access-Control-Allow-Methods:GET,HEAD,POST < - 忽略我指定的方法Access-Control-Allow-Origin:* < - 我的指定原点被忽略Access- Control-Max-Age:1800 Content-Length:0 Date:Day,dd Mon yyyy hh:mm:ss GMT Vary:Origin Vary:Access-Control-Request-Method Vary:Access-Control-Request-Headers
1 回答
Spring文档和许多示例都缺少这个,但答案很简单 . 我刚刚在CorsRegistry上看到了allowCredentials()方法,并将.allowCredentials(true)添加到注册表方法链中,并重新添加了Access-Control-Allow-Credentials标头 .
此外,我不再使用已弃用的WebMvcConfigurerAdapter,但现在实现WebMvcConfigurer并覆盖addCorsMappings()方法 .