'Error during WebSocket handshake: Unexpected response code: 403

I have implemented WebSockets with Spring Boot Application and have the below error message when trying to test the ws connection with the chrome extension 'Smart websocket client'. However, I have no problem when run the Spring Boot Application locally.

WebSocket connection to 'ws://192.168.X.XYZ:8080/test' failed: 
Error during WebSocket handshake: Unexpected response code: 403

The only difference which I see is in the Request headers:

In the one it works - Origin:http://192.168.X.XYZ:8080

In the one it does not work - Origin:chrome-extension://omalebghpgejjiaoknljcfmglgbpocdp

What I did in the WebSocketConfig class is below:

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(myHandler(), "/test").setAllowedOrigins("http://192.168.X.XYZ:8080");
}

and still does not work.

Could you please advise what the reason for that error might be and how to fix it?

Thank you in advance.



Solution 1:[1]

You need to configure your "chrome-extension://..." origin as an allowed origin or even "*", otherwise it's rejected by the server.

Solution 2:[2]

On update to spring boot 2.4, it also requires:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*");
        }
    };
}

and @EnableAutoConfiguration on the config class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian Clozel
Solution 2 Ahmed Ashour