Не удается подключиться к серверу websocket (весна) - PullRequest
0 голосов
/ 18 февраля 2020

Я пытаюсь реализовать простой websocket с Stomp (а не Sock Js) с сервером Spring и Angular клиентом.

Вот мой код для включения websocket в Spring:

@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractSecurityWebSocketMessageBrokerConfigurer {

    @Bean
    public TaskScheduler heartBeatScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker('/status').setHeartbeatValue(new long[] { 10000, 10000})
                .setTaskScheduler(heartBeatScheduler());

        registry.setApplicationDestinationPrefixes('/');
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint('/myapp-websocket).setAllowedOrigins("*");
    }

    @Override
    protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
        messages.anyMessage().authenticated();
    }

    @Override
    protected boolean sameOriginDisabled() {
        return true;
    }
}

Но я не могу подключиться к нему, когда я пытаюсь angular с stomp js, соединение никогда не устанавливается. Когда я тестирую с помощью wscat wscat -c "ws://localhost:4200/api/myapp-websocket" (кстати, / api / is good), ответа нет, он всегда пытается соединиться без успеха.

Что здесь не так?

Редактировать: Здесь это две зависимости, которые я использую

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-messaging</artifactId>
    </dependency>

Редактировать:

Я также пытаюсь изменить messages.anyMessage().authenticated(); на messages.anyMessage().permitAll();, но такое же поведение я все еще не могу подключить к своей веб-розетке ..

1 Ответ

1 голос
/ 21 февраля 2020

Я полагаю, вы отправляете клиентские запросы из другого порта, это означает, что ваш клиент находится в другом источнике, для этого вы должны добавить некоторые заголовки на стороне сервера. Также при подключении websocket отправляет POST в конечную точку, которую вы должны включить. Я не знаю точно, какие конечные точки отправляются, проверьте вашу консоль, а затем добавьте их в antMatchers

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
            .and()

           .csrf().disable().authorizeRequests()
            .antMatchers("/status**", "/topic", "/myapp-websocket/**")
            .permitAll()
            .anyRequest()
            .authenticated();

    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
          CorsConfiguration config = new CorsConfiguration();
          config.setAllowedOrigins(ImmutableList.of("*"));
          config.setAllowCredentials(true);
          config.setAllowedMethods(ImmutableList.of("HEAD",
                    "GET", "POST", "PUT", "DELETE", "PATCH"));
          config.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
           UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", config);
            return source;
        }
}
...