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

Spring Security 6集成WebSocket遇连接问题及JWT集成咨询

问题:添加Spring Security后WebSocket连接失败及JWT集成疑问

一、初始无安全配置的WebSocket项目(运行正常)

Controller代码

@RestController
public class Controller {
    private final SimpMessagingTemplate template;

    public Controller(SimpMessagingTemplate template) {
        this.template = template;
    }

    @PostMapping("/sendLong")
    public void sendLong(@RequestParam("id") Long id) {
        template.convertAndSend("/topic/long", id);
    }
}

WebSocket配置类

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

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

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
    
}

客户端HTML代码

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Test</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.0/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
</head>
<body>
    <script>
        const sock = new SockJS('http://localhost:8080/ws');
        const stompClient = Stomp.over(sock);
        
        stompClient.connect({}, (frame) => {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/long', (message) => {
                console.log('Received: ' + message.body);
            });
        });
    </script>
</body>
</html>

二、添加安全配置后连接失败

添加以下两个配置类后,WebSocket连接失败:

安全配置类

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .cors()
                .and()
                .csrf()
                .disable()
                .authorizeHttpRequests()
                .anyRequest()
                .permitAll()
                .and()
                .build();
    }
}

WebSocket安全配置类

@Configuration
@EnableWebSocketSecurity
public class WebSocketSecurityConfig {

    @Bean
    AuthorizationManager<Message<?>> messageAuthorizationManager(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
        messages
                .anyMessage().permitAll();
        return messages.build();
    }
}

已尝试放开所有端点权限,还试过以下配置(误以为是CSRF问题,但无效):

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
    argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
}

@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
    AuthorizationManager<Message<?>> myAuthorizationRules = AuthenticatedAuthorizationManager.anonymous();
    AuthorizationChannelInterceptor authz = new AuthorizationChannelInterceptor(myAuthorizationRules);
    AuthorizationEventPublisher publisher = new SpringAuthorizationEventPublisher(this.context);
    authz.setAuthorizationEventPublisher(publisher);
    registration.interceptors(new SecurityContextChannelInterceptor(), authz);
}

疑问

  • 连接失败的问题出在哪里?
  • 后续计划集成JWT过滤器,在Spring Boot 3和Security 6环境下,WebSocket如何获取JWT令牌?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:22:44