我正在尝试在 Node.js 中使用 Socket.IO,并尝试允许服务器为每个 Socket.IO 客户端提供身份。由于套接字代码超出了 http 服务器代码的范围,因此无法轻松访问发送的请求信息,因此我假设它需要在连接期间发送。最好的方法是什么
1) 向服务器获取有关谁通过 Socket.IO 连接的信息
2) 验证他们所说的身份(我目前正在使用 Express,如果这能让事情变得更容易的话)
最佳答案
使用 connect-redis 并将 redis 作为所有经过身份验证的用户的 session 存储。确保在身份验证时将 key (通常是 req.sessionID)发送给客户端。让客户端将此 key 存储在 cookie 中。
在套接字连接时(或以后的任何时间)从 cookie 中获取此 key 并将其发送回服务器。使用此键获取 redis 中的 session 信息。 (获取 key )
例如:
服务器端(使用 redis 作为 session 存储):
req.session.regenerate...
res.send({rediskey: req.sessionID});
客户端:
//store the key in a cookie
SetCookie('rediskey', <%= rediskey %>); //http://msdn.microsoft.com/en-us/library/ms533693(v=vs.85).aspx
//then when socket is connected, fetch the rediskey from the document.cookie and send it back to server
var socket = new io.Socket();
socket.on('connect', function() {
var rediskey = GetCookie('rediskey'); //http://msdn.microsoft.com/en-us/library/ms533693(v=vs.85).aspx
socket.send({rediskey: rediskey});
});
服务器端:
//in io.on('connection')
io.on('connection', function(client) {
client.on('message', function(message) {
if(message.rediskey) {
//fetch session info from redis
redisclient.get(message.rediskey, function(e, c) {
client.user_logged_in = c.username;
});
}
});
});
关于authentication - Socket.IO 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4753957/