错误内容
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.
原因
这个错误信息是关于 Spring Framework 中 CORS (跨域资源共享) 配置的变更。具体来说,当 allowCredentials 设置为 true 时,不允许使用通配符 "*" 作为 allowedOrigins 的值。
这个变更从 Spring Framework 5.3.0 版本开始引入(对应 Spring Boot 2.4.0)。在此版本之前,虽然技术上允许这样的配置,但实际上浏览器不会接受这种组合(Access-Control-Allow-Origin: * 和 Access-Control-Allow-Credentials: true),因为这是 W3C CORS 规范明确禁止的。
从 Spring 5.3.0/Spring Boot 2.4.0 开始,框架主动阻止了这种无效配置,并提供了以下解决方案:
明确列出所有允许的起源(而不是使用 ) 使用 allowedOriginPatterns 属性,它支持更灵活的模式匹配(例如 http://.example.com)
解决方法
把这样子
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(Boolean.TRUE);
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
改成这样子
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(Boolean.TRUE);
config.setAllowedOriginPatterns(List.of("*"));