Socket.io重新授权

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

你应该可以通过启用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来执行检查在一定的时间间隔。