Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 406
Johnyb Avatar asked Sep 04 '26 21:09

Johnyb


1 Answers

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);

    }

}

like image 179
jacky-neo Avatar answered Sep 06 '26 12:09

jacky-neo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!