1

在授权发生很久之后,我正在尝试将 cookie 传输回服务器。原因是我想在套接字打开一段时间后检查用户是否仍然登录。有没有办法用socket.io做到这一点?也许通过再次强制授权;这可能吗?

4

1 回答 1

2

您应该能够通过启用 socket.io 授权来做到这一点。一旦启用,它将在 socket.io 连接时调用提供的函数。

这是我不久前使用的一些代码,可以帮助您入门。

var connect = require('connect');

// these should be the same as you use for setting the cookie
var sessionKey = "yourSessionKey"; 
var sessionSecret = "yourSessionSecret";

socketIO.set('authorization', function (data, accept) {
    // check if there's a cookie header
    if (data.headers.cookie) {
        // if there is, parse the cookie
        data.cookie = connect.utils.parseSignedCookies(cookie.parse(decodeURIComponent(data.headers.cookie)), sessionSecret);
        if (!data.cookie[sessionKey]) return accept('No cookie value for session key ' + sessionKey, false);
        var parts = data.cookie[sessionKey].split('.');
        data.sessionId = parts[0];

        // at this point you would check if the user has been authenticated 
        // by using the session id as key. You could store such a reference
        // in redis after the user logged in for example.

        // you might want to set the userid on `data` so that it is accessible
        // through the `socket.handshake` object later on
        data.userid = username;

        // accept the incoming connection
        return accept(null, true);
    } else {
       // if there isn't, turn down the connection with a message
       // and leave the function.
       return accept('No cookie transmitted.', false);
    }
});

一旦设置了data属性(例如data.userid在上面的示例中),您就可以通过socket.handshake对象访问它们。例如:

io.sockets.on('connection', function (socket) {
    var userId = socket.handshake.userid;

    socket.on('reauthorize-user', function(){
         // check the user status using the userId then emit a socket event back
         // to the client with the result
         socket.emit('reauthorization-result', isAuthorized);
    });
});

在客户端上,您只需发出reauthorize-user事件并收听该reauthorization-result事件。您显然可以有一个 setTimeout 来以特定的时间间隔执行检查。

于 2012-11-07T23:14:37.457 回答