Spring Boot配置WebMvcConfigurer后仍出现WebSocket CORS错误怎么解决
根因说明
你配置的WebMvcConfigurer跨域规则仅适用于Spring MVC管理的普通HTTP接口,WebSocket握手阶段的HTTP请求由Spring WebSocket模块单独处理,不会复用MVC层的跨域配置,这是触发CORS错误的核心原因。
排查步骤
- 确认WebSocket握手请求的Origin值是否与你配置的允许跨域源完全匹配,排除协议(http/https)拼写错误、端口不匹配、域名前后带空格等低级问题
- 检查项目是否集成了Spring Security,若集成需确认Security规则是否已放行WebSocket握手请求的OPTIONS预检请求,是否存在Security层CORS规则覆盖自定义配置的情况
- 检查现有WebSocket端点的注册代码,是否已经配置了跨域规则,规则内容是否符合预期
解决方案
方案1:原生WebSocket端点配置
如果你使用@EnableWebSocket手动注册原生WebSocket端点,在注册时添加跨域规则即可:
@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandler customHandler, WebSocketHandlerRegistry registry) { registry.addHandler(customHandler, "/ws/your-endpoint") // 此处配置和MVC层一致的允许跨域源即可 .allowedOrigins("http://localhost:8080","origin2","origin3") // Spring Boot 2.4+版本如果需要用通配符,使用allowedOriginPatterns替代 // .allowedOriginPatterns("http://*.your-domain.com") .withSockJS(); // 仅使用SockJS时保留该行 } }
方案2:STOMP over WebSocket配置
如果你使用@EnableWebSocketMessageBroker实现STOMP协议的WebSocket服务,在端点注册时添加跨域规则:
@Configuration @EnableWebSocketMessageBroker public class StompWebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws/stomp-endpoint") .allowedOrigins("http://localhost:8080","origin2","origin3") .withSockJS(); // 仅使用SockJS时保留该行 } // 其他STOMP消息代理、前缀配置省略 }
方案3:Spring Security集成补充配置
如果项目集成了Spring Security,需额外在Security规则中放行WebSocket路径并开启CORS支持:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() // 开启CORS支持,自动适配你配置的跨域规则 .authorizeRequests() .antMatchers("/ws/**").permitAll() // 放行所有WebSocket相关路径 // 其余自定义Security规则省略 .anyRequest().authenticated(); } }
内容的提问来源于stack exchange,提问作者Paulo Cordeiro
相关产品推荐
相关产品推荐

