Johnyb
Johnyb

Reputation: 1316

Error during WebSocket handshake: Unexpected response code: 400 Spring boot websockets

I am trying to implement websockets. My code:

In spring security i allow the path w/e authentitcation

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/register","/login","/testAuth","/web","/ws").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

And config for ws

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new WsMessageHandler(), "/ws")
                .addInterceptors(new CustomInterceptor())
                .setAllowedOrigins("*")
                .setHandshakeHandler(new DefaultHandshakeHandler())
                .withSockJS();
    }
}

`

  public class CustomInterceptor implements HandshakeInterceptor {
        @Override
        public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
            return true;
        }
    
        @Override
        public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, @Nullable Exception e) {
    
        }
    }

As client i use simple js code:

var exampleSocket = new WebSocket("ws://localhost:8080/ws", "protocolOne");
           exampleSocket.onopen = function() {
              
              // Web Socket is connected, send data using send()
              ws.send("Message to send");
              alert("Message is sent...");
           };

However i recieve error:

WebSocket connection to 'ws://localhost:8080/ws' failed: Error during WebSocket handshake: Unexpected response code: 400

What is causing this? Everything should be correct. Thanks for answer

Upvotes: 5

Views: 8359

Answers (2)

frankenstein
frankenstein

Reputation: 1

there is an issue in your client side code, yu don't need to pass ws, instead make it http enter image description here

heere you can see that http followed by localhost and port if not you rdefault port and then path that you have configured

Upvotes: 0

jacky-neo
jacky-neo

Reputation: 853

I find your code has some error:

  1. if you use WebSocket() as client, you should comment withSocktJS() in WebSocketConfig. and like it
@Configuration
@EnableWebSocket
public class WebSocketConfig2 implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new WsMessageHandler(), "/ws")
                .addInterceptors(new CustomInterceptor())
                .setAllowedOrigins("*")
                .setHandshakeHandler(new DefaultHandshakeHandler())
//                .withSockJS()
        ;
    }
}

  1. Your client js code is wrong. there is no ws. You should use exampleSocket to send. like as below
                var exampleSocket = new WebSocket("ws://localhost:8081/ws", "protocolOne");
                exampleSocket.onopen = function(ws) {
                    console.log('-----------------', ws);
                    // Web Socket is connected, send data using send()
                    exampleSocket.send("Message to send");
                    alert("Message is sent...");
                };

  1. You point a protocol called 'protocolOne' when sending websocket in client, you should return it back in CustomInterceptor. You can do as below.
public class CustomInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, @Nullable Exception e) {
        if(serverHttpRequest.getHeaders() == null )
            return ;
        if(serverHttpRequest.getHeaders().get("Sec-WebSocket-Protocol") == null)
            return ;
        String protocol = (String) serverHttpRequest.getHeaders().get("Sec-WebSocket-Protocol").get(0);
        if(protocol == null)
            return ;

        serverHttpResponse.getHeaders().add("Sec-WebSocket-Protocol", protocol);

    }

}

Upvotes: 12

Related Questions