我正在尝试将 cookie 传回服务器,在授权发生很久之后。原因是我想检查在套接字打开一段时间后用户是否仍然登录。有没有办法用 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 以特定时间间隔执行检查。
关于javascript - Socket.io 重新授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13279676/