Spring WebSocket Connecting with SockJS to a different domain Spring WebSocket Connecting with SockJS to a different domain spring spring

Spring WebSocket Connecting with SockJS to a different domain


Jax's anwesr was correct :)

The registerStompEndpoints method gives us the opportunity to set the Allowed Origins. We need to add it before the "withSockJs()" option.

    @Override    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {        stompEndpointRegistry.addEndpoint("/BO/socket").setAllowedOrigins("*").withSockJS();    }


To anyone getting to this ticket because of the 403 Forbidden answer when trying to connect through a SockJsClient to a different domain:

The problem arises when trying to make a GET to the /info Url, as part of the handshaking. The response actually returns a 200 via WGET as well as via browser. Only through SockJsClient it doesn't work.

After trying different solutions, the only one that really fixed the issue is to write a class that implements Transport and InfoReceiver. In this way the developer can directly handle this part of the handshake.Basically you make the work in the executeInfoRequest() method:

@Overridepublic String executeInfoRequest(URI infoUrl, HttpHeaders headers) {    HttpGet getRequest = new HttpGet(infoUrl); // eventually add headers here    HttpClient client = HttpClients.createDefault();    try {        HttpResponse response = client.execute(getRequest);        List<String> responseOutput = IOUtils.readLines(response.getEntity().getContent());        return responseOutput.get(0);    } catch (IOException ioe) {        ...    }}

I defined TransportType.XHR as transport type.


In my case, I had to add these configuarations to get SockJS / STOM to work with CORS:

@Configuration@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer{    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**")                .allowedOrigins("*")                .allowCredentials(false)                .maxAge(3600)                .allowedHeaders("Accept", "Content-Type", "Origin", "Authorization", "X-Auth-Token")                .exposedHeaders("X-Auth-Token", "Authorization")                .allowedMethods("POST", "GET", "DELETE", "PUT", "OPTIONS");    }}