I tried many different solutions and posts since I'm new to websockets (for example: Spring Boot + Sockjs client offline connecting issues or Spring boot Websocket without SockJS). My current setup looks like this:
Frontend side (plain JS):
const stomp = Stomp.over(() => new SockJS('http://localhost:8080/websockets'));
stomp.activate();
Backend side (Spring Boot):
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websockets").setAllowedOrigins("*");
registry.addEndpoint("/websockets").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/queue");
config.setApplicationDestinationPrefixes("/ws");
}
}
After spending hours trying to proxy requests and fighting with CORS, above is currently the core that should allow me to simply connect to my websocket. Unfortunately .active() on the frontend side results in the following:
Any ideas?
EDIT: That's how the response and request headers look like (why is only a GET method allowed?):
My Spring Security configuration:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().ignoringAntMatchers("/websockets/**").and().authorizeRequests()
.anyRequest().permitAll().and()
.exceptionHandling(e -> e.authenticationEntryPoint(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
))
.oauth2Login()
.defaultSuccessUrl("/api/users/createAccount", true);
return http.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setExposedHeaders(List.of("*"));
configuration.addAllowedOrigin("http://localhost:5173");
configuration.addAllowedMethod(HttpMethod.GET);
configuration.addAllowedMethod(HttpMethod.POST);
configuration.addAllowedHeader("*");
configuration.setAllowCredentials(true);
configuration.applyPermitDefaultValues();
source.registerCorsConfiguration("/api/**", configuration);
source.registerCorsConfiguration("/websockets/**", configuration);
source.registerCorsConfiguration("/login", configuration);
return source;
}
}