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!