Socket.IO 认证 [英] Socket.IO Authentication

查看:43
本文介绍了Socket.IO 认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Node.js 中使用 Socket.IO,并尝试允许服务器为每个 Socket.IO 客户端提供一个身份.由于套接字代码超出了 http 服务器代码的范围,因此无法轻松访问发送的请求信息,因此我假设需要在连接期间将其发送出去.最好的方法是什么

I am trying to use Socket.IO in Node.js, and am trying to allow the server to give an identity to each of the Socket.IO clients. As the socket code is outside the scope of the http server code, it doesn't have easy access to the request information sent, so I'm assuming it will need to be sent up during the connection. What is the best way to

1) 将有关谁通过 Socket.IO 连接的信息发送给服务器

1) get the information to the server about who is connecting via Socket.IO

2) 验证他们所说的是谁(我目前正在使用 Express,如果这让事情变得更容易)

2) authenticate who they say they are (I'm currently using Express, if that makes things any easier)

推荐答案

使用 connect-redis 并将 redis 作为所有经过身份验证的用户的会话存储.确保在身份验证时将密钥(通常为 req.sessionID)发送给客户端.让客户端将此密钥存储在 cookie 中.

Use connect-redis and have redis as your session store for all authenticated users. Make sure on authentication you send the key (normally req.sessionID) to the client. Have the client store this key in a cookie.

在套接字连接上(或以后的任何时间)从 cookie 中获取此密钥并将其发送回服务器.使用这个键在redis中获取会话信息.(获取密钥)

On socket connect (or anytime later) fetch this key from the cookie and send it back to the server. Fetch the session information in redis using this key. (GET key)

例如:

服务器端(以redis作为会话存储):

Server side (with redis as session store):

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;
      });
    }

  });
});

这篇关于Socket.IO 认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆