How can I get (Express's) sessionID for a websocket connection

前端 未结 2 2010
温柔的废话
温柔的废话 2020-12-23 12:25

I\'m using WebSockets npm install ws on the same port as Express is running.

I\'d like to pick up the associated \'sessionID\' from the HTTP connection

2条回答
  •  萌比男神i
    2020-12-23 13:26

    This was a nightmare, finally got it working for myself using signed cookies!

    Set up your store (example memory store):

    var MemoryStore = express.session.MemoryStore;
    store = new MemoryStore();
    

    Expose parseCookie as global (if you need it in other modules) like this in app / server js files:

    app.use(parseCookie = express.cookieParser('secret'));
    

    Now set up sockets:

    //this method gets called later
    var ensureAuthenticatedSocket = function(handshake, callback) {
        cookie = cookieParser(handshake, null, function(err) {
            var sessionID = handshake.signedCookies['sid'];
            store.get(sessionID, function(err, session) {
                callback(err, session);
            });
        });
    };
    //listen time
    io = io.listen(server);
    //configure authentication
    io.configure(function() {
        io.set('authorization', function(handshake, callback) {
            //call the method with handshake as parameter, wait for callback
            ensureAuthenticatedSocket(handshake, function(err, session) {
                if (!err && session) {
                    //no error + found session = wicked!
                    callback(null, true);
                } else {
                    callback(null, false);
                }
            });
        });
    });
    ...
    //more socket code
    

提交回复
热议问题