Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access session identifier when using Socket.IO?

I have a chat, and I need to manage unique connections. I searched around, but the solutions that I have found all appear to be deprecated.

So, how would I get a socket's session ID with Socket.IO?

I'm using Node.js, Express.js and Socket.IO.

like image 963
viniciuswebdev Avatar asked Sep 29 '13 20:09

viniciuswebdev


1 Answers

Use the Socket.IO authentication setting, and pass the cookies to the cookie parser middleware from Express. Once the cookie is parsed, you can get the session ID of the client, and fetch the associated session from the session store, whether it is a memory story or other type of store.

// we need to use the same secret for Socket.IO and Express
var parseCookie = express.cookieParser(secret);
var store = /* your MemoryStore, RedisStore, etc */;

io.set('authorization', function(handshake, callback) {
  if (handshake.headers.cookie) {
    // pass a req, res, and next as if it were middleware
    parseCookie(handshake, null, function(err) {
      handshake.sessionID = handshake.signedCookies['connect.sid'];
      // or if you don't have signed cookies
      handshake.sessionID = handshake.cookies['connect.sid'];

      store.get(handshake.sessionID, function (err, session) {
        if (err || !session) {
          // if we cannot grab a session, turn down the connection
          callback('Session not found.', false);
        } else {
          // save the session data and accept the connection
          handshake.session = session;
          callback(null, true);
        }
      });
    });
  } else {
    return callback('No session.', false);
  }
  callback(null, true);
});

Each time a client attempts to connect, the authorization function is run. It takes the handshake header cookies (handshake.headers.cookies), and passes them to express.cookieParser(). The cookie parser then finds the session ID, and then searches the store for the associated session. Then, we store the associated session into handshake.session, so we can access it like this:

app.get('/', function(req, res) {
  req.session.property = 'a value';
});

io.sockets.on('connection', function(socket) {
  var session = socket.handshake.session;
  session.property // a value
});
like image 64
hexacyanide Avatar answered Sep 22 '22 11:09

hexacyanide