ZBLOG

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 "all...

这个错误是 Spring Framework 在处理 CORS (跨域资源共享) 配置时出现的。当你在 Spring Boot 或 Spring Web 应用中配置 CORS 并同时设置了 allowCredentials=trueallowedOrigins="*" 时,就会出现这个错误。

错误原因:

根据 CORS 安全规范,当响应头包含 Access-Control-Allow-Credentials: true(表示允许携带认证信息如 cookies)时:

  1. 不能使用通配符 *:浏览器不允许将 Access-Control-Allow-Origin 设为 *(必须明确指定域名)。
  2. 必须显式声明来源:需要明确列出允许的域名列表。

解决方案:

方案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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23381

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?