authentication - Socket.IO 认证

标签 authentication node.js express socket.io

我正在尝试在 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/

相关文章:

java - Netty 的基本身份 validator

java - 服务是否应该包含登录用户作为参数?

javascript - 读取包含在 promise 中的对象的属性的正确方法是什么? (获取类型错误)

node.js - Node 骑士异步不起作用?

javascript - 获取 Express 中的 Requests 数量

javascript - 在express js 4.4.1中压缩文件(gzip)

ios - 需要将 firebase 匿名帐户链接到 firebase 上的 google 登录或 facebook 登录帐户

security - Spark 独立集群的身份验证

node.js - 努力在 Node js 中用 Knex 编写一个 SELECT 查询来进行计算

node.js - 在 Express 路径中获取文件类型