Websockets 在尝试连接 websocket 时使用 "SockJS+spring websocket" 错误(404:找不到 STOMP 端点的路径)

Websockets using "SockJS+spring websocket" error when trying to connect the websocket (404: path of STOMP endpoint not found)

在我的网络应用程序中,我尝试使用 SockJS 连接到 websocket,但返回了一条错误消息(找不到 404 路径“/stomp/info”):

这个问题被问了很多次,但我找不到适合我的情况的答案 谁能帮我找到解决办法?

这是我的代码

- 服务器端基于 spring 网络流量,spring 安全性 (JWT) [spring 引导版本:2.1.2RELEASE]

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

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

    @Override

    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry
                .addEndpoint("/stomp")
                .setAllowedOrigins("http://localhost:4200")
                //.setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
        DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
        resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);

        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setObjectMapper(new ObjectMapper());
        converter.setContentTypeResolver(resolver);

        messageConverters.add(converter);

        return false;
    }
}

CORSFilter.java

@Configuration
@EnableWebFlux
public class CORSFilter implements WebFluxConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .exposedHeaders("Access-Control-Allow-Origin",
                        "Access-Control-Allow-Methods",
                        "Access-Control-Allow-Headers",
                        "Access-Control-Max-Age",
                        "Access-Control-Request-Headers",
                        "Access-Control-Request-Method")
                .maxAge(3600)
                .allowCredentials(false);
    }
}

WebSecurityConfig.java

@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
@Configuration
public class WebSecurityConfig {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private SecurityContextRepository securityContextRepository;

    @Bean
    public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
        return http
                .cors().and().headers().frameOptions().disable().and()
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .authenticationManager(authenticationManager)
                .securityContextRepository(securityContextRepository)
                .authorizeExchange()
                .pathMatchers(HttpMethod.OPTIONS).permitAll()
                .pathMatchers("/login","/stomp","/stomp/**","/stomp/info","/stomp/info/**").permitAll()
                .anyExchange().authenticated()
                .and().build();
    }
}

- 客户端基于Angular (stompjs + sockjs-client)

socketConnect() {
    const socket = new SockJS('http://localhost:8081/stomp');
    this.stompClient = StompJS.Stomp.over(socket);

    const _this = this;
    this.stompClient.connect({}, function (frame) {
      console.log('Connected: ' + frame);
      _this.stompClient.subscribe('/prob/' + _this.id + '/newcomment', function (data) {
        console.log(data);
      });
    });
  }

更新

我更改了 CORS 过滤器的配置:

@Configuration
public class CORSFilter{
    @Bean
    CorsWebFilter corsWebFilter(){
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:4200");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);

        return new CorsWebFilter(source);
    }

但是我还有一个错误:

GET http://localhost:8081/stomp/info?t=1602859336795 404 (not found)

服务器端websocket初始化日志如下:

2020-10-16 15:41:14.712  INFO 13060 --- [  restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler     : Starting...
2020-10-16 15:41:14.712  INFO 13060 --- [  restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler     : BrokerAvailabilityEvent[available=true, SimpleBrokerMessageHandler [DefaultSubscriptionRegistry[cache[0 destination(s)], registry[0 sessions]]]]
2020-10-16 15:41:14.714  INFO 13060 --- [  restartedMain] o.s.m.s.b.SimpleBrokerMessageHandler     : Started.
...
2020-10-16 15:42:13.750  INFO 13060 --- [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats    : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]

最后我找到了问题, 问题是我为 spring-mvc 而不是 spring-webflux 使用了 websocket 配置,我找到了一个很好的教程来在 spring-webflux 的反应上下文中实现 websocket :enter link description here