如何在socket.io上访问会话数据(node-client-sessions)?

时间:2013-08-27 21:10:05

标签: node.js session express socket.io

我的应用中的会话数据由node-client-sessions处理(如Using secure client-side sessions to build simple and scalable Node.JS applications中所述),现在我有socket.io(websockets)来处理一些实时功能。我想通过握手时的会话数据对登录用户进行身份验证。但是,在握手时,socket.io为我们提供了这个handshakeData对象,并且它不会完全暴露请求对象。我需要访问请求的会话属性。有什么想法吗?

我正在使用expressjs(nodejs)。

更新

Inspired @ LaurentPerrin的回答我潜入客户端会话源并发现了解密和编码功能。也许不像直接使用我的会话对象那么容易,但到目前为止非常有效。

我的代码,到目前为止:

/*jslint node: true, es5: true, nomen: true, unparam: true */

'use strict';

var encode = require('client-sessions').util.encode,
    decode = require('client-sessions').util.decode,
    cookie = require('cookie'),

    cookieSettings = require('./persistors/cookieSettings'),

    authorized = {
        'me@domain.com': 1
    };

module.exports = function websocket(io) {
    io.set('authorization', function (handshakeData, callback) {
        var session_data;
        if (!handshakeData.headers.cookie) {
            callback({
                status: 'forbidden',
                reason: 'no session',
                source: 'socket_io'
            }, false);
            return;
        }
        session_data = decode(cookieSettings, cookie.parse(handshakeData.headers.cookie).session).content;
        if (authorized[session_data.email]) {
            handshakeData.session_data = session_data;
            callback(null, true);
        } else {
            // callback({
            //     status: 'forbidden',
            //     reason: 'unauthorized',
            //     source: 'socket_io'
            // }, false);
            callback(null, false);
        }
        return;
    });
    io.set('transports', ['websocket', 'flashsocket']);
    io.sockets.on('connection', function (socket) {
        console.log('connected')
        socket.on('credenciamento', function (data) {
            console.log(socket.handshake.session_data.email);
            socket.broadcast.emit('credenciamento', {
                inscrito_id: data.inscrito_id
            });
        });
    });
};

这绝不是完整的。但授权部分似乎工作得很好。 =)

现在,关于回调函数。起初我像@LaurentPerrin一样使用它,传递带有错误响应的对象。但它会产生警告。 Socket.io认为发生了错误:

warn - handshake error [object Object]

所以在第二时刻,我在未授权时将null作为第一个参数传递:

info - handshake unauthorized

考虑到socket.io理解每个东西的方式,第二种方式似乎在语义上更正确。 =)

我选择第二种方式。自己选一个。

1 个答案:

答案 0 :(得分:4)

不确定它是否完全相同,但我在我的案例中写了这个。请注意,我需要直接使用明确的依赖项来避免版本问题。

var cookie = require('express/node_modules/cookie'),
    parseSignedCookie = require('express/node_modules/connect').utils.parseSignedCookie,
    parseJSONCookie = require('express/node_modules/connect').utils.parseJSONCookie;

…

io.set('authorization', authorizeSocket);

…

function authorizeSocket(handshake, done) {
  if (!handshake.headers.cookie)
    return done({status: 'forbidden', reason: 'no session', source: 'socket_io'}, false);

  var cookies = cookie.parse(handshake.headers.cookie),
      signed = cookies['your_session_cookie'];

  if (!signed)
    return done({status: 'forbidden', reason: 'tampered cookie', source: 'socket_io'}, false);

  var raw = parseSignedCookie(signed, 'your_session_secret'),
  json = parseJSONCookie(raw);

  if (!json || !json.passport || !json.passport.user)
    return done({status: 'forbidden', reason: 'bad session', source: 'socket_io'}, false);

  // finally...
  var user = json.passport.user;

  handshake.user = user;

  done(null, true);
}