我正在尝试在授权发生很久之后将cookie传回服务器。原因是我想在套接字打开一段时间后检查用户是否仍然登录。有没有办法用socket.io做到这一点?也许再次强制授权;这有可能吗?
答案 0 :(得分: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以特定间隔执行检查。