Spring Boot中WebSocket连接遭遇401 Status Code未授权错误求助
Spring Boot WebSocket 401未授权问题排查与解决建议
核心原因分析
只要你的Spring Boot项目引入了spring-boot-starter-security依赖,Spring Security就会默认启用全局认证保护,所有HTTP请求(包括WebSocket握手阶段的HTTP请求)都会被拦截要求授权,这是触发401的最常见原因。
具体排查与解决步骤
1. 确认依赖情况
检查pom.xml中是否存在Spring Security依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
如果存在,必须针对性配置Security规则放行WebSocket端点;若项目完全不需要认证功能,可直接移除该依赖(生产环境不推荐此操作)。
2. 修正Spring Security配置
之前的配置无效大概率是路径匹配错误或未适配WebSocket握手逻辑,以下是通用的正确配置示例:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // WebSocket握手请求通常不携带CSRF令牌,关闭CSRF校验避免拦截 .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth // 替换为你的实际WebSocket端点路径,比如"/ws/**"匹配所有ws开头的端点 .requestMatchers("/ws/**").permitAll() // 其他业务请求根据需求配置认证规则 .anyRequest().authenticated() ); return http.build(); } }
- 注意:如果使用STOMP协议(配置了
@EnableWebSocketMessageBroker),需要放行的是握手端点(通常是"/ws"),而非订阅/发布路径("/topic/**"等)。
3. 核对WebSocket端点配置
确保WebSocketConfig中注册的端点路径与Security放行的路径完全匹配:
@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { // 这里的"/ws/chat"要和Security中放行的路径一致 registry.addHandler(new MyWebSocketHandler(), "/ws/chat") .setAllowedOrigins("*"); // 测试阶段允许跨域,生产环境需指定具体域名 } }
4. 调整Postman测试方式
- 测试WebSocket时,Postman需选择
WebSocket协议(而非HTTP),输入地址格式为ws://localhost:8080/ws/chat(替换为你的实际端口和端点)。 - 若Postman缓存了旧的认证信息,建议清空缓存或使用无痕窗口测试,避免干扰。
5. 排查自定义拦截/过滤器
如果项目中存在自定义的过滤器或拦截器,检查是否拦截了WebSocket握手请求,需确保对应的端点路径被放行。
内容的提问来源于stack exchange,提问作者Bianca Ciobanu
相关产品推荐
相关产品推荐

