开发者

Unable to get connect's session id from cookie using websockts with socket.io

开发者 https://www.devze.com 2023-03-27 13:17 出处:网络
In the configuration of a socket.io server I have the following code which grabs the session id from the cookie in the header and I want to verify that session corresponds with a logged in user (I\'m

In the configuration of a socket.io server I have the following code which grabs the session id from the cookie in the header and I want to verify that session corresponds with a logged in user (I'm using express as the http server, and a MemoryStore to store sessions).

  io.set('authorization', function (handshakeData, callback) {
    var cookies = handshakeData.headers.cookie;
    cookies = connect.utils.parseCookie(cookies);
    var sid = cookies['connect.sid'开发者_如何学Go];  
    /* verify that is a valid session */
  });

This works when I connect to my node.js from Firefox which ends up using long-polling, but fails when I connect from Chrome which uses WebSockets. The reason it doesn't work is Chrome doesn't send a cookie in the header at all when the client code connects to the socket.

Is there anyway to get Chrome to send the cookie over WebSockets?

If not how should I store the sessionID so that it can be accessed when authenticating a socket connection?

I should also note that the cookie keeping the session id is set to http-only, which I've seen elsewhere could be the problem? My understanding is that be removing that option increases your vulnerability to XSS attacks?

Thanks for your help!


Not familiar with that particular behavior of Chrome's. However, its pretty hard to guarantee that you're going to get a cookie with things like Flash sockets, which socket.io may fall back on.

You could, however, send the session id manually over the wire with socket.io when you connect, using something like https://github.com/carhartl/jquery-cookie or just plain accessing the cookie via javascript (e.g. document.cookie). You'd be guaranteed to have it that way, regardless of transport.


Try disabling flash sockets and web sockets on your client:

        var socket = new io.Socket(null, {
              rememberTransport: false,
              transports: [
                  //'websocket', 
                  //'flashsocket',
                  'htmlfile',
                  'xhr-multipart',
                  'xhr-polling']
            })

        socket.on('connect',
            function() {
                console.log(arguments);
            }
        );

        socket.on('message',
            function(data) {
                console.log(arguments);
            }
        );
0

精彩评论

暂无评论...
验证码 换一张
取 消