【问题标题】:Websockets using "SockJS+spring websocket" error when trying to connect the websocket (404: path of STOMP endpoint not found)尝试连接 websocket 时使用“SockJS+spring websocket”的 Websockets 错误(404:STOMP 端点的路径未找到)
【发布时间】:2021-01-29 09:35:28
【问题描述】:

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

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

这是我的代码

- 服务器端基于spring webflux, spring security (JWT) [spring boot version: 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(未找到)

这是服务器端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]

【问题讨论】:

  • 我在这里猜测,但.cors().and().headers().frameOptions().disable().and() 不起作用,尝试.cors().disable().and()..... 或者尝试删除您自己的cors 配置并使用spring security cors 过滤器并根据docs.spring.io/spring-security/site/docs/current/reference/… 进行配置
  • @ThomasAndolf 我尝试了您的解决方案,但仍然无法正常工作
  • 请用您尝试过的所有方法、所有 DEBUG 日志以及您是否调试过 Spring CORS 过滤器来更新您的问题?
  • @ThomasAndolf 我通过添加日志更新了问题,感谢您的 cmets :)
  • 你还没有发布 DEBUG 日志,或者 Spring Security 的 DEBUG 日志

标签: java websocket spring-webflux sockjs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-07-04
    • 2016-11-14
    • 2017-06-05
    • 2015-08-10
    • 2016-03-21
    • 2017-10-04
    • 2019-08-12
    • 2016-11-09
    • 2020-12-28
    相关资源
    最近更新 更多