16

我在npm install wsExpress 运行的同一端口上使用 WebSockets。

我想从刚刚建立并升级到 WebSocket 的 HTTP 连接中获取关联的“sessionID”。

// start express listening
server.listen(conf.server.port, conf.server.host);

var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({server: server});

wss.on('connection', function(ws) {
    var sessionID = // how do I get this?
    ws.on('message', function(message) {
        console.log('received: %s', message);
    });
    ws.send('something');
});

如何才能做到这一点?

(我目前通过在页面中发送 sessionID 来解决这个问题,但这很难看。)

4

2 回答 2

16
  1. 解析 cookie
  2. 获取会话 ID
  3. 获取会话数据

    var express = require('express');
    var parseCookie = express.cookieParser();
    var MemoryStore = express.session.MemoryStore;
    
    var store = new MemoryStore();
    
    app.configure(function() {
        app.use(express.session({ store: store, secret: '123456', key: 'sid' }));
    });
    
    wss.on('connection', function(ws) {
        parseCookie(ws.upgradeReq, null, function(err) {
            var sessionID = ws.upgradeReq.cookies['sid'];
            store.get(sessionID, function(err, session) {
                // session
            });
        }); 
    
        ws.on('message', function(message) {
            console.log('received: %s', message);
        });
        ws.send('something');
    });
    
于 2012-07-18T13:45:15.670 回答
7

这是一场噩梦,终于使用签名的 cookie 为自己工作了!

设置您的存储(示例内存存储):

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

在应用程序/服务器 js 文件中将 parseCookie 公开为全局(如果您在其他模块中需要它):

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

现在设置套接字:

//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
于 2013-06-01T18:35:03.873 回答