java - 弹簧靴。CORS。'allowCredentials = false' 不起作用
问题描述
我的 Spring Boot (2.4.4) 应用程序中有下一个 CORS 配置:
@Configuration
public class CORSConfiguration {
@Bean
public WebMvcConfigurer cors() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
}
在某个时间点,我开始遇到下一个异常:
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
之后,我根据答案修复了我的配置:
registry.addMapping("/**").allowedOriginPatterns("*");
之后,CORS 的问题就消失了。据我了解,我不能使用allowedOrigins("*")
with allowCredentials(true)
。好的,很清楚。但是我根本没有添加allowCredentials(true)
我的代码。也许这是默认值(?)。
然后我决定用下一种方式编写我的配置:
registry.addMapping("/**").allowCredentials(false).allowedOrigins("*");
CORS 和异常的问题又回来了。尽管allowCredentials(true)
我将以下值指定为allowCredentials(false)
. 我错了什么?allowCredentials
或者为什么 Spring在某些情况下会覆盖 的值?
我失败的 CORS 请求
请求标头:
OPTIONS /list/1054/participant-list/info HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type
Referer: http://localhost:13000/
Origin: http://localhost:13000
Connection: keep-alive
响应标头:
HTTP/1.1 500
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,POST
Access-Control-Allow-Headers: content-type
Access-Control-Max-Age: 1800
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0
Date: Tue, 06 Jul 2021 14:15:16 GMT
Connection: close
解决方案
试试这个,并确保添加客户端的正确来源,并将所需的允许方法放在那里。我只是随意放在那里
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:13000")
.allowedMethods("HEAD","GET","POST","PUT","DELETE","PATCH").allowedHeaders("*");
}
推荐阅读
- mysql - 数据库触发器 - 当更新行中的字段等于三个值之一时,更新另一个表
- php - 使用正则表达式捕获评论
- php - php copy() 复制多个文件时关闭连接
- javascript - 从 S3 getObject() 中检索图像不起作用
- amazon-web-services - 为 AWS ELB 生成公有/后端密钥
- java - android上的socket.io服务器
- git - Git revert 删除我的仓库中的每个文件
- javascript - 如何使用 javascript 创建 elementor 块
- java - 将 pdf 作为静态资源从在 docker 容器中运行的 spring 应用程序提供
- angular6 - 当我在组件的提供者中添加服务时出现没有提供者错误