Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cookie inside websocket connection

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');
});
like image 303
mqklin Avatar asked Aug 28 '16 12:08

mqklin


People also ask

Can WebSockets use cookies?

Websockets will carry the browser cookie to server at the start and the server will verify if this value exists in the memory store.

Can WebSocket be proxied?

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.

How do I authenticate a WebSocket?

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.

Does WebSocket go through load balancer?

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.


1 Answers

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.

like image 139
jfriend00 Avatar answered Sep 19 '22 09:09

jfriend00