如何获取(Express)的websID以进行websocket连接

时间:2012-07-18 12:51:45

标签: node.js websocket express

我在Express正在运行的同一端口上使用WebSockets npm install ws

我想从刚刚建立并升级到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来解决此问题,但这很难看。)

2 个答案:

答案 0 :(得分:14)

  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');
    });
    

答案 1 :(得分:6)

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

设置商店(示例内存存储):

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

在app / server 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