这个错误是 Spring Framework 在处理 CORS (跨域资源共享) 配置时出现的。当你在 Spring Boot 或 Spring Web 应用中配置 CORS 并同时设置了 allowCredentials=true
和 allowedOrigins="*"
时,就会出现这个错误。
错误原因:
根据 CORS 安全规范,当响应头包含 Access-Control-Allow-Credentials: true
(表示允许携带认证信息如 cookies)时:
- 不能使用通配符
*
:浏览器不允许将Access-Control-Allow-Origin
设为*
(必须明确指定域名)。 - 必须显式声明来源:需要明确列出允许的域名列表。
解决方案:
方案1:明确指定允许的域名(推荐)
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com", "http://localhost:8080") // 显式列出域名
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}
方案2:使用 allowedOriginPatterns
(Spring Boot 2.4+)
如果确实需要动态匹配多个域名,可以用正则表达式模式:
registry.addMapping("/**")
.allowedOriginPatterns("*") // 或更具体的模式如 "https://*.example.com"
.allowCredentials(true)
.allowedMethods("*");
方案3:通过过滤器动态设置(灵活控制)
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("https://trusted-domain.com"); // 动态添加逻辑可在此实现
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new FilterRegistrationBean<>(new CorsFilter(source));
}
关键区别:
配置项 | 作用 |
---|---|
allowedOrigins |
严格匹配域名列表,不支持通配符 * (与 allowCredentials=true 冲突) |
allowedOriginPatterns |
支持通配符和正则表达式(如 *.example.com ),适用于动态域名场景 |
Why?
这是浏览器的安全策略要求:RFC标准规定,若需传输凭据(cookies/auth headers),服务端必须明确声明可信任的来源而非使用通配符。
内容由零声教学AI助手提供,问题来源于学员提问