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

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

问题描述

我想在Node.js的使用Socket.IO,并正尝试允许服务器给一个身份到每个Socket.IO客户端。由于插座code是HTTP服务器code的范围之内,它不容易接触到发送请求信息,因此我假设它需要在连接期间发送的。什么是最好的办法。

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)验证,他们说他们是谁(我目前使用防爆preSS,如果让事情变得更容易)

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

推荐答案

使用连接的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的会话信息。 (GET键)

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天全站免登陆