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

SockJS无法连接Spring Boot WebSocket,求解决方案

WebSocket连接失败问题求助

刚接触WebSocket,尝试多种方案后仍无法建立连接,当前相关配置及问题如下:

前端(原生JS)

const stomp = Stomp.over(() => new SockJS('http://localhost:8080/websockets'));

stomp.activate();

后端(Spring Boot)

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websockets").setAllowedOrigins("*");
        registry.addEndpoint("/websockets").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/queue");
        config.setApplicationDestinationPrefixes("/ws");
    }
}

调试代理请求与CORS问题后,理论上应可建立连接,但调用stomp.activate()时触发错误:浏览器控制台提示Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:8080/websockets/info?t=xxx'。

补充:请求响应头显示仅允许GET方法,不符合SockJS连接的方法需求。

Spring Security配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().ignoringAntMatchers("/websockets/**").and().authorizeRequests()
                .anyRequest().permitAll().and()
                .exceptionHandling(e -> e.authenticationEntryPoint(
                        new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
                ))
                .oauth2Login()
                .defaultSuccessUrl("/api/users/createAccount", true);

        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setExposedHeaders(List.of("*"));
        configuration.addAllowedOrigin("http://localhost:5173");
        configuration.addAllowedMethod(HttpMethod.GET);
        configuration.addAllowedMethod(HttpMethod.POST);
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);
        configuration.applyPermitDefaultValues();
        source.registerCorsConfiguration("/api/**", configuration);
        source.registerCorsConfiguration("/websockets/**", configuration);
        source.registerCorsConfiguration("/login", configuration);
        return source;
    }
}

恳请提供解决思路。


解决思路

  • 补充CORS允许的请求方法:SockJS建立连接时会用到OPTIONS方法,当前CORS仅允许GET和POST,需添加OPTIONS方法,或直接允许所有方法:
    // 方式1:添加OPTIONS方法
    configuration.addAllowedMethod(HttpMethod.OPTIONS);
    // 方式2:允许所有方法
    configuration.addAllowedMethod("*");
    
  • 修正WebSocket端点注册冲突:后端重复注册了/websockets端点,建议统一配置(保留带SockJS的即可),同时避免通配符*与AllowCredentials=true的冲突(浏览器不允许两者同时使用):
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websockets").setAllowedOrigins("http://localhost:5173").withSockJS();
    }
    
  • 验证Spring Security的CORS优先级:Spring Security的CORS配置会覆盖WebSocket端点的CORS设置,确保/websockets/**的CORS配置包含所有必要方法与正确源。
  • 排查CSRF配置:虽然已忽略/websockets/**的CSRF,但可临时关闭全局CSRF测试是否为问题根源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:35:24