使用Express.js v4和Socket.io v1的会话

rac*_*erp 6 javascript session node.js express socket.io

如何在express.js中保存会话数据并在socket.io事件中访问它?

我正在使用express.js v4,socket.io v1和基本的快速会话中间件开发webapp .

我花了几个小时试图解决这个问题,但Stack Overflow上的所有当前答案仅适用于express v3和socket.io v0.9.不幸的是我不能使用express.io,因为它只是一个使用旧版本的包装器.

我目前的解决方案是完全破解:

app.get('/auth', function(req, res) {
    if(verified(req.query)) {
        authed[req.sessionID] = true;
    }
});

io.sockets.on('connection', function(websocket) {
    var cookies = cookie.parse(websocket.handshake.headers.cookie);
    var decrypted = cookieParser.signedCookies(cookies, random);
    var sessionID = decrypted['connect.sid'];

    websocket.on('input', function(input) {
        if(authed[sessionID]) {
            // Do stuff...
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我将基于会话ID的"会话数据"保存在对象中作为键/值存储.这适用于单个流程应用程序,但它确实不是一个好的解决方案.它实际上并没有让我访问req.session中保存的任何内容,并且如果进程结束,我保存的所有数据都将丢失.

最重要的是,我需要加载第三方cookie包来解析socket.io中的cookie字符串.似乎新版本的cookie-parser消除了它从字符串中解析cookie的功能.至少,它没有记录.

必须有更好的方法!

编辑:最后,我决定使用express redis并在socket.io中编写一个函数,以便根据会话ID从redis获取信息.

Mar*_*rco 1

您可以将会话存储在 Memcached 或 Redis 中。然后您可以从这些存储之一获取会话数据。

memcache 和 redis 包都可用于 Nodejs。

另请注意,您可以在 socket.io 中使用中间件进行身份验证。然后,您不必将身份验证逻辑放入连接事件处理程序中。

var authorization = require('./socket/authorization')(app);
io.use(authorization.authorize);
Run Code Online (Sandbox Code Playgroud)

举个例子,这个 memcached auth 的东西在我们的例子中是读取我们的 php 存储的 cookie。

var memcached = require('memcached'),
    cookie = require('cookie),
    debug = require('debug')('socket.io:authorization');

module.exports = function(app) {
    var authorize = function(socket, next) {
        var handshakeData = socket.request;
        if (handshakeData.headers.cookie) {
            handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
            if (typeof handshakeData.cookie['node'] === 'undefined') {
                next(new Error('No cookie transmitted.'));
            } else {
                var loginEndIndex = handshakeData.cookie['node'].indexOf(',');
                handshakeData.node = handshakeData.cookie['node'].slice(0, loginEndIndex);

                var memcached = new Memcached(app.config.memcached.server, app.config.memcached.options);
                memcached.on('failure', function(details) {
                    debug('Server: %s went down due to %s', details.server, details.messages.join(' '));
                });
                memcached.on('reconnecting', function(details) {
                    debug('Total downtime caused by server %s: %sms', details.server, details.totalDownTime);
                });

                memcached.get(handshakeData.cookie['PHPSESSID'], function(err, result) {
                    if (!err && result !== false) {
                        var pipeIndex = result.indexOf('|'),
                            phpData = result.slice(pipeIndex + 1),
                            obj = php.unserialize(phpData);

                        if (handshakeData.node === obj.userLogin) {
                            debug('coockie-accepted: %s, %s', handshakeData.node, obj.userLogin);
                            next();
                        } else {
                            debug('cookie-revoked; %s, %s', handshakeData.node, obj.userLogin);
                            next(new Error('Cookie is invalid.'));
                        }
                    } else {
                        debug('error: %s', err);
                        next(new Error('Cookie is invalid.'));
                    }
                    memcached.end();
                });
            }
        } else {
            debug('error: No cookie transmitted.');
            next(new Error('No cookie transmitted.'));
        }
    };

    return {
        authorize: authorize
    };
};
Run Code Online (Sandbox Code Playgroud)