You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot配置Stomp时Access-Control-Allow-Origin多值报错如何解决

Spring Boot Stomp SockJS连接CORS多值报错解决方案

问题原因

触发报错的核心原因是CORS响应头重复添加:

  • 你同时配置了STOMP端点级别的CORS规则和全局Spring MVC CORS规则,两层配置都会往响应中插入Access-Control-Allow-Origin头,导致返回的头值出现https://domain.work, *多个值的情况,违反浏览器CORS策略
  • 你配置了setAllowCredentials(true),该场景下不允许使用*作为允许的源值,也不允许多个源值同时存在

解决步骤

步骤1:统一CORS配置入口,避免两层同时配置

推荐保留全局CORS配置,调整STOMP端点的CORS配置,避免重复加头:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry
    .addEndpoint("/agent")
    // 移除原有的setAllowedOrigins配置,改用setAllowedOriginPatterns适配带凭证的请求
    .setAllowedOriginPatterns("*")
    .withSockJS();
    logger.info("out register");
}

步骤2:调整全局CORS配置,兼容凭证请求

Spring Boot 2.4+版本中,setAllowedOrigins不支持同时配置通配符和allowCredentials=true,需替换为setAllowedOriginPatterns:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    logger.info("thong tin domain allowed: "+ domainAllowed);
    CorsConfiguration configuration = new CorsConfiguration();
    // 替换setAllowedOrigins为setAllowedOriginPatterns
    configuration.setAllowedOriginPatterns(Arrays.stream(domainAllowed.split(","))
            .map(String::trim)
            .collect(Collectors.toList()));
    configuration.setAllowCredentials(true);
    configuration.setMaxAge(-1L);
    configuration.setAllowedMethods(Arrays.asList("*"));
    // 补充允许的请求头配置,避免部分请求被拦截
    configuration.setAllowedHeaders(Arrays.asList("*"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

步骤3:检查配置项&反向代理规则

  • 确认domainAllowed配置中没有混入*值,所有允许的源都是完整的域名格式(如https://cli.ovp.vn)
  • 如果你用了Nginx等反向代理,检查代理配置中有没有额外添加Access-Control-Allow-Origin头,避免和代码配置叠加

内容的提问来源于stack exchange,提问作者dohv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:36:03