hieunguyennvvt
hieunguyennvvt

Reputation: 11

How to fix CORS error when connecting WebSocket via STOMP in Spring Boot?

I am building a chat application using Spring Boot and JavaScript, but I am getting an error:

Access to XMLHttpRequest at 'http://localhost:8080/ws/chat/info?t=1689700945725' ↗ from origin 'http://localhost:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my code...

SecurityConfig:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .csrf(AbstractHttpConfigurer::disable)
            .cors(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers("/user/**").permitAll()
                    .anyRequest().authenticated()
            )
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

StompConfig:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws/chat").setAllowedOrigins("http://localhost:5501").withSockJS();
}

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

and client:

var socket = new SockJS('http://localhost:8080/ws/chat', null, {
    headers: {
        Authorization: 'Bearer ' + jwt
    }
});
stompClient = Stomp.over(socket);
stompClient.connect({}, onConnected, onError);

I tried using setAllowedOriginPatterns("http://localhost:5501"), but it didn't work.

Upvotes: 1

Views: 740

Answers (1)

CH Liu
CH Liu

Reputation: 1884

Your client connects to the port 8080, but the allowed origin is set to 5501. They should be the same in this case.

Upvotes: -1

Related Questions