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

使用Tyrus客户端连接Spring Boot WebSocket服务器时出现403握手异常求助

WebSocket握手异常排查:403错误(Tyrus Client 连接Spring Boot WebSocket)

报错信息

Caused by: org.glassfish.tyrus.websockets.HandshakeException: Response code was not 101: 403

客户端代码

final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();

ClientManager client = ClientManager.createClient();
client.connectToServer(new Endpoint() {

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        try {
            session.addMessageHandler((MessageHandler.Whole<String>) message -> {
                System.out.println("Received message: "+message);
            });
            session.getBasicRemote().sendText(SENT_MESSAGE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}, cec, new URI("ws://localhost:8080/websocket"));
} catch (Exception e) {
    e.printStackTrace();
}

排查与解决步骤

  • 检查Spring Security权限拦截
    若Spring Boot项目启用了Spring Security,WebSocket端点默认会被拦截。需在安全配置中放行WebSocket路径:

    // Spring Security 5.7+ 无配置类写法
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests(auth -> auth
                .requestMatchers("/websocket/**").permitAll()
                .anyRequest().authenticated()
            )
            .build();
    }
    

    旧版本(5.7以下)可继承WebSecurityConfigurerAdapter实现配置。

  • 确认端点路径一致性
    核对客户端连接的ws://localhost:8080/websocket与服务器端WebSocket配置的路径是否完全匹配。服务器端示例配置:

    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(myWebSocketHandler(), "/websocket")
                    .setAllowedOrigins("*"); // 测试环境放开跨域,生产需指定具体域名
        }
    
        @Bean
        public WebSocketHandler myWebSocketHandler() {
            return new MyWebSocketHandler();
        }
    }
    
  • 配置跨域允许规则
    若客户端与服务器存在跨域场景(如端口不同),需在WebSocket配置中明确允许的源,避免因跨域校验返回403。生产环境不要用*,指定具体域名更安全。

  • 添加必要的握手请求头
    若服务器端要求身份验证头(如Token),需在Tyrus Client的配置中添加请求头:

    ClientEndpointConfig cec = ClientEndpointConfig.Builder.create()
            .configurator(new ClientEndpointConfig.Configurator() {
                @Override
                public void beforeRequest(Map<String, List<String>> headers) {
                    headers.put("Authorization", Collections.singletonList("Bearer your-auth-token"));
                }
            })
            .build();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:45:23