Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript websocket client adding cookie to header

I am creating a websocket upgrade request in javascript and need to add a cookie for adding an authentication token, is this possible with cross domain restrictions? My implementation is pretty basic:

document.cookie="token="+authToken+";domain=www.test.com;path=/";
websocket = new WebSocket(endpoint);
like image 772
not_rafay Avatar asked Jul 15 '15 00:07

not_rafay


People also ask

Can WebSockets use cookies?

It is not recommended as WebSockets are not restrained by the same-origin policy. Using cookies could actually leave users vulnerable to cross-site scripting attacks (xss).

Can WebSockets have headers?

Warning: The server can't send more than one Sec-Websocket-Protocol header. If the server doesn't want to use any subprotocol, it shouldn't send any Sec-WebSocket-Protocol header. Sending a blank header is incorrect.

Can a client have multiple WebSocket connections?

A server can open WebSocket connections with multiple clients—even multiple connections with the same client.

Can a single WebSocket handle text and binary data?

WebSocket enables bidirectional, message-oriented streaming of text and binary data between client and server.


1 Answers

You should change the way how you set the cookies value. There is no way to add the domain and path values of the cookies, they are added automatically. You should add just the nameOfProperty and valueOfProperty. See the simple example below:

 document.cookie = "FirstProperty=FirstPropertyValue";
 document.cookie = "SecondProperty=SecondPropertyValue";

 const ws = new WebSocket('ws://localhost:2427/health');
like image 87
Viktor Balykhin Avatar answered Oct 17 '22 01:10

Viktor Balykhin