Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send cookies when connecting to socket.io via WebSockets?

Is there a way to easily pass an authentication cookie when handshaking a WebSocket connection to socket.io? I currently have to do it separately, like so:

socket = new io.Socket(document.location.hostname);
socket.addEvent("connect", function()
{
    // Send PHP session ID, which will be used to authenticate
    var sessid = readCookie("PHPSESSID");
    this.send("{'action':'authenticate','sessionid':'"+sessid+"'}");
});
like image 944
Luke Dennis Avatar asked Nov 30 '10 06:11

Luke Dennis


People also ask

Are cookies sent over WebSockets?

Although, in theory, one could use cookies, as all WebSocket connections start with an HTTP request (with an upgrade header on it), and the cookies for the domain you are connecting to, will be sent with that initial HTTP request to open the WebSocket.

How do you set cookies on a WebSocket?

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.

How do I send cookies from server to client?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

How does Socket.IO connect to client server?

listen(port); // Create a Socket.IO instance, passing it our server var socket = io. listen(server); // Add a connect listener socket. on('connection', function(client){ console. log('Connection to client established'); // Success!


1 Answers

WebSockets do have support for cookies since they are based on HTTP, but a quick browse through the source of Socket.IO revealed that there is no support for this built in.

So using cookies directly is not a feasible solution in this case, also, since you're using Socket.IO, it's not guaranteed that users will actually connect via a WebSocket.

In the case that a connection uses a flash socket, it's really hard to make Flash send the Browser's cookies instead of it's own set, so even if you would send a cookie directly, it wouldn't get set in the Browser in case of a flask socket connection.

Currently there's no support for this built into Socket.IO, so flash sockets will just fail.

You can read about that in this issue, and here's a question about the flash cookie problem.

Best solution is still to make it part of your own protocol.

like image 179
Ivo Wetzel Avatar answered Sep 28 '22 08:09

Ivo Wetzel