javaspringwebsocketspring-websocketsockjs

Spring WebSocket: Discrepancy in CORS Behavior between XMLHttpRequest and Fetch Requests despite Credentials Set to False


I have configured Credentials to false in my Spring WebSocket application. However, when I request http://192.168.7.175/api/webSocketEndPoint/info?t=17139606, the response status is 200. Despite this, CORS issues arise, and the following error is logged:

Access to XMLHttpRequest at 'http://192.168.7.175/api/webSocketEndPoint/info?t=1713960686964' from origin 'http://192.168.7.175:9092' 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.

Strangely, when I use fetch('http://192.168.7.175/api/webSocketEndPoint/info?t=17139606'), it returns a 200 status without any CORS errors. My server is implemented using Spring WebSocket, and the client makes requests using sockJs.

What could be causing this discrepancy in CORS behavior between the two methods of making requests?

Note: We shouldn't set 'allow-credentials' to true because of CSRF attacks, right?


Solution

  • According to spring documentation here you should always set Access-Control-Allow-Credentials header to true, so you can't use sockjs with this header set to false.

    Alternatively you can use Javascript WebSocket API.