I try to implement plain websocket with Stomp (and not SockJS) with a Spring server and an Angular client.
Here is my code to enable websocket in 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;
}
}
But I can't connect to it, when I try in angular with stompjs the connection is never done.
When I test with wscat wscat -c "ws://localhost:4200/api/myapp-websocket"
(the /api/ is good btw) there is no response, it's always trying to connect without success.
What is wrong here ?
Edit: Here is the two dependency I use
<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>
Edit:
I also try to change messages.anyMessage().authenticated();
to messages.anyMessage().permitAll();
but same behavior I still can't connect to my websocket..
I suppose you send client requests from different port, that means your client is on different origin, for that you must add some headers on server side. Also on connect websocket sends POST to endpoint, which you must enable. I don't know exactly what endpoints are being sent, check in you console, and then add them to 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;
}
}