I know that I can set cookies during handshake:
const wss = new WebSocketServer({ server, path: '/ws' });
wss.on('headers', headers => {
headers.push('Set-Cookie: my-cookie=qwerty');
});
How can I change cookies inside websocket connection? For example, I want to set session cookie after some client message:
ws.on('message', () => {
// something like ws.setCookie('my-cookie=qwerty');
});
Websockets will carry the browser cookie to server at the start and the server will verify if this value exists in the memory store.
WebSocket communication can take successfully take place in the presence of forward proxies, providing the client and proxy server have been configured properly to deal with it. This page explains how to configure a Universal Messaging JavaScript client and Apache serving as a forward proxy to permit WebSocket use.
Authentication FlowThe server generates a temporary external authentication token, stores it in the Authentication Cache, and returns it to the client. The client makes a WebSocket handshake request with the external authentication token passed as a query-string parameter in the handshake endpoint URL.
The load balancer knows how to upgrade an HTTP connection to a WebSocket connection and once that happens, messages will travel back and forth through a WebSocket tunnel. However, you must design your system for scale if you plan to load balance multiple WebSocket servers.
You can't set a cookie upon receipt of a webSocket message because it's not an http request. Once the webSocket connection has been established, it's an open TCP socket and the protocol is no longer http, thus there is no built-in way to exchange cookies.
You can send your own webSocket message back to the client that tells it to set a cookie and then be listening for that message in the client and when it gets that message, it can set the cookie in the browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With