使用Node / Express / Socket.IO进行身份验证 [英] Authentication with Node/Express/Socket.IO

查看:169
本文介绍了使用Node / Express / Socket.IO进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到HTML文件的节点/ socket.io / express服务器(如 so )。所以访问网址可以将您连接到服务器。我正在尝试建立一个系统,在这种情况下,服务器一次在多台计算机上运行,​​并通过某种用户名和密码认证,访问具有特定凭据的网页将您连接到其中一台具有相同功能的计算机运行服务器的凭据。



从以前的类似问题中我们看到提到Redis,但是它们很旧,我想知道是否有更新的或更好的方式来实现

解决方案

由于Express 4是新的,所以您不会找到很多最新的文档,所以让我尝试在这里补救:



Express 4.x和Socket.IO 1.x

中的身份验证

让我们开始混淆我想你所做的:




  • 什么是Redis? p>

    Redis是一个数据结构引擎。它允许您存储键/值对,没有更多(在这种情况下)。在建立身份验证系统时,您可以为您进行唯一的操作是存储数据,用户信息,会话ID等。在您的情况下,您可以在多台计算机之间共享商店,就像您共享一个数据库一样,或者一个文本文件。



    Redis


  • 将用户验证到节点/快递服务器



    您可以做的一个方法是使用 护照 护照是专用于Node.js上的身份验证的中间件。它与Express相容易使用。有一个关于如何通过快速申请设置护照的优秀教程系列,所以我不会详细说明这一部分,请花时间浏览这个系列,这是非常宝贵的知识。

    这里是链接第一部分,这是我将重点关注的下一步。


  • 将socket.io添加到混合



    Socket.io无法访问您在第1部分中创建的会话Cookie。为了补救,我们将使用 passport-socketio 模块。



    Passport-socketio需要一个本地会话存储,而不是内存存储。这意味着我们需要一些方法将会话数据存储在某个地方,那是响铃吗?



    确切地说, Redis



    您可以尝试其他商店,如mongoDB或MySQL,但Redis是最快的。



    ,我会假设您的快速应用程序和护照已经开始运作,并将重点放在应用程序中添加socket.io。


  • 设置: / strong>




  var session = require('express-session') ; //你应该已经在你的应用程序中有这个行
var passportSocketIo = require(passport.socketio);
var io = require(socket.io)(server);
var RedisStore = require('connect-redis')(session);

var sessionStore = new RedisStore({//创建会话商店
主机:'localhost',
端口:6379,
});

app.use(session({
store:sessionStore,//告诉快递在Redis存储中存储会话信息
secret:'mysecret'
}) );

io.use(passportSocketIo.authorize({// configure socket.io
cookieParser:cookieParser,
secret:'mysecret',//确保它和一个你给表达
存储:sessionStore,
成功:onAuthorizeSuccess,// *可选*回调成功
失败:onAuthorizeFail,// *可选*回调失败/错误
}));

Connect-redis 是一个会话存储包,使用redis(如果名称不明显)。




  • 最终步骤



  function onAuthorizeSuccess(data,accept ){
console.log('connect to socket.io');
accept(); //让用户通过
}

函数onAuthorizeFail(数据,消息,错误,接受){
if(error)accept(new Error(message));
console.log('connect to socket.io:',message);
accept(null,false);
}

io.sockets.on('connection',function(socket){
console.log(socket.request.user);
});

在socket.request中找到的用户对象将包含记录的所有用户信息在用户中,您可以从此处传递它,或者从此处执行所需的任何操作。



注意:此设置将稍微不同于Socket.IO< 1.x


I have a node/socket.io/express server that's connected to a HTML file (like so). So visiting the web address connects you to the server. I am trying to set up a system where by, said server is being run on multiple computers at a time and by way of some sort of username and password authentication, visiting the webpage with specific credentials connects you to one of the computers with those same credentials running the server.

Ive seen mention of "Redis" from previous similar questions but they are pretty old and im wondering if there is a newer or better way of achieving this.

解决方案

You won't find a lot of up-to-date documentation since Express 4 is kind of new, so let me try to remedy that here :

Authentication in Express 4.x and Socket.IO 1.x

Let's start with a confusion I think you're making:

  • What is Redis?

    Redis is a data structure engine. It allows you to store key/values pairs, nothing more (In this context). The only thing it can do for you when building your authentication system is storing the data, user info, session ids, etc. In your case, you can share a store between multiple machines, the same way you'd share a database, or a text file.

    Redis

  • Authenticate user to node/express server

    One of the ways you can do that is by using passport. Passport is a middleware dedicated to authentication on Node.js. It is made for use with Express and relatively easy to setup. There is an excellent tutorial series on how to setup passport with your express application, so I won't detail this part, please take the time to go through the series, it's invaluable knowledge.

    Here's the link to the first part, which is the one I'll focus on for the next step.

  • Add socket.io to the mix

    Socket.io doesn't have access to the session cookies that you create in part 1. To remedy that, we will use the passport-socketio module.

    Passport-socketio requires a local session store, as opposed to a memory store. This means we need some way to store the session data somewhere, does that ring a bell?

    Exactly, Redis.

    You can try other stores, like mongoDB or MySQL, but Redis is the fastest.

    In this example, I'll assume that your express app and passport are already operational and will focus on adding socket.io to the app.

  • Setup :

var session = require('express-session'); //You should already have this line in your app
var passportSocketIo = require("passport.socketio");
var io = require("socket.io")(server);
var RedisStore = require('connect-redis')(session);

var sessionStore = new RedisStore({ // Create a session Store
   host: 'localhost',
   port: 6379,
});

app.use(session({
  store: sessionStore,  //tell express to store session info in the Redis store
  secret: 'mysecret'
}));

io.use(passportSocketIo.authorize({ //configure socket.io
   cookieParser: cookieParser,
   secret:      'mysecret',    // make sure it's the same than the one you gave to express
   store:       sessionStore,        
   success:     onAuthorizeSuccess,  // *optional* callback on success
   fail:        onAuthorizeFail,     // *optional* callback on fail/error
}));

Connect-redis is a session store package that uses redis (in case the name isn't obvious).

  • Final step :

function onAuthorizeSuccess(data, accept){  
  console.log('successful connection to socket.io');
  accept(); //Let the user through
}

function onAuthorizeFail(data, message, error, accept){ 
  if(error) accept(new Error(message));
  console.log('failed connection to socket.io:', message);
  accept(null, false);  
}

io.sockets.on('connection', function(socket) {
  console.log(socket.request.user); 
});

The user object found in socket.request will contain all the user info from the logged in user, you can pass it around, or do whatever you need with it from this point.

Note : This setup will be slightly different for Socket.IO < 1.x

这篇关于使用Node / Express / Socket.IO进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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