1

I'm setting up a web service that provides both authentication and a WebSocket interface. The API of the server needs to be accessible cross-domain and still receive the cookie set for the server's domain. In fetch, this is possible with the option credentials: "include" and it works well. Is there an equivalent for WebSocket?

Basically, I have a Node.js server running on a.com:

let app = require("express")()
// ...
//headers
app.use((req, res, next) => {
  console.log(req.headers)
  console.log(req.protocol)
  // Allow multiple origins from config
  let origin = req.headers.origin
  if (config.allowedOrigins.includes(origin)) {
    res.setHeader("Access-Control-Allow-Origin", origin)
  }
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  res.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,PATCH,DELETE")
  res.setHeader("Access-Control-Allow-Credentials", true)
  res.setHeader("Access-Control-Expose-Headers", "X-Total-Count, Link")
  next()
})
// ...
app.ws("/", (ws, req) => {
  const sessionID = req.sessionID // should be the same sessionID for requests from all origins
  // ...
})
// ...

from web application hosted on b.com:

let socket = new WebSocket("wss://a.com") // should include cookie from a.com

This works well when I test it locally and everything's running on localhost, but fails when the web application is running on a different domain.

I'd like to have the possibility that the user logs in on a.com, but can use the same session for a WebSocket request from b.com.

I'm thankful for every suggestion!

1 Answers1

1

I've figured this out by now. The following assumes that third-party cookies are enabled:

The default behavior, at least in all major browsers I've tested, is that the existing cookie will be sent with the WebSocket request (i.e. exactly as I wanted it). The browser I was using where I encountered the issue is Brave. Brave seems to have a bug that Cookies are not added to WebSocket connections. So it wasn't an issue in the first place, just a bug in the particular browser I was using.

When third-party cookies are blocked though (as they are by default in Safari), I don't think there is a way to achieve what I'd like to achieve.