socket.io parse connect (>= 2.4.1) signed session

2019-03-15 09:48发布

With the latest version of connect (as of 2012-07-26), I've found the following way to get a session ID from socket.io that will work with a connect-redis store.

var express = require('express')
, routes = require('./routes')
, fs = require('fs')
, http = require('http')
, io = require('socket.io')
, redis = require('connect-redis')
, connect = require('express/node_modules/connect')
, parseSignedCookie = connect.utils.parseSignedCookie
, cookie = require('express/node_modules/cookie');

var secret = '...';
var rStore = new(require('connect-redis')(express));

//...

var server = http.createServer(app);
var sio = io.listen(server);

sio.set('authorization', function(data, accept) {
    if(data.headers.cookie) {
        data.cookie = cookie.parse(data.headers.cookie);
        data.sessionID = parseSignedCookie(data.cookie['connect.sid'], secret);
    } else {
        return accept('No cookie transmitted', false);
    }
    accept(null, true);
});

data.sessionID can then be used later such as

sio.sockets.on('connection', function(socket) {
    console.log('New socket connection with ID: ' + socket.handshake.sessionID);
    rStore.get(socket.handshake.sessionID, function(err, session) {
        //...
    });
});

Having to import so many from express (connect, a utility of connect, and the cookie module) seems like an overly roundabout way of getting the functions needed to parse connect's signed cookies. Has anyone found another way?

1条回答
何必那么认真
2楼-- · 2019-03-15 10:18

I was running into the same and just wrote a tiny module to abstract it. Here's how its usage looks like. It was written and tested using express 3 so should work fine with connect 2.4.x. Please let me know otherwise.

var SessionSockets = require('session.socket.io')
  , sessionSockets = new SessionSockets(io, sessionStore, cookieParser);

sessionSockets.on('connection', function (err, socket, session) {
  //your regular socket.io code goes here
});

For more details on how it works see https://github.com/wcamarao/session.socket.io

查看更多
登录 后发表回答