Dolis
Dolis

Reputation: 335

Spring websocket with VueJs - blocked by CORS

I am trying to find a solution on how to connect VueJs and Spring via WebSocket.

WebSocket conf (Spring)

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket")
                .setAllowedOrigins("http://localhost:8080")
                .withSockJS();
    }

I have tried few options with .setAllowedOrigins(""), like "*", "http://localhost:8080" or don't use it.

I have CORS conf in my project also.

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

In my CORS conf I have tried many options, but without result :(

And the last thing is the client-side connection (VueJs):

connect() {
      this.socket = new SockJS("http://localhost:8081/gs-guide-websocket");
      this.stompClient = Stomp.over(this.socket);
      this.stompClient.connect(
        {},
        frame => {
          this.connected = true;
          console.log(frame);
          this.stompClient.subscribe("/topic/chat/1", tick => {
            console.log(tick);
            this.received_messages.push(JSON.parse(tick.body).content);
          });
        },
        error => {
          console.log(error);
          this.connected = false;
        }
      );
    }

And on everything I have tried, I am receiving this error:

Access to XMLHttpRequest at 'http://localhost:8081/gs-guide-websocket/info?t=1583167396687' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Is there any solution that I can use to make it work?

FYI:

Thanks for your help all :)

Upvotes: 1

Views: 1744

Answers (1)

Dolis
Dolis

Reputation: 335

I was so close. Everything here is right (not for the production of course).

The last thing that was missing in CORS conf was to set Allow credentials to true.

I hope this post will help you :)

Upvotes: 1

Related Questions