简体   繁体   English

使用Node / Express / Socket.IO进行身份验证

[英]Authentication with Node/Express/Socket.IO

I have a node/socket.io/express server that's connected to a HTML file (like so ). 我有一个连接到HTML文件的node / socket.io / express服务器( 如此 )。 So visiting the web address connects you to the server. 因此,访问Web地址会将您连接到服务器。 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. 我见过以前类似的问题提到“Redis”,但它们已经很老了,我想知道是否有更新或更好的方法来实现这一点。

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 : 你不会找到很多最新的文档,因为Express 4是一种新的,所以让我试着在这里解决这个问题:

Authentication in Express 4.x and Socket.IO 1.x Express 4.x和Socket.IO 1.x中的身份验证

Let's start with a confusion I think you're making: 让我们从一个混乱开始,我认为你正在制造:

  • What is Redis? 什么是Redis?

    Redis is a data structure engine. Redis是一个数据结构引擎。 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. 在构建身份验证系统时,它唯一能为您做的就是存储数据,用户信息,会话ID等。在您的情况下,您可以在多台计算机之间共享存储,就像共享数据库一样,或者一个文本文件。

    Redis 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. Passport是一个专门用于Node.js身份验证的中间件。 It is made for use with Express and relatively easy to setup. 它适用于Express,相对容易设置。 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添加到混合中

    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. Socket.io无权访问您在第1部分中创建的会话cookie。为了解决这个问题,我们将使用passport-socketio模块。

    Passport-socketio requires a local session store, as opposed to a memory store. Passport-socketio需要本地会话存储,而不是内存存储。 This means we need some way to store the session data somewhere, does that ring a bell? 这意味着我们需要某种方式将会话数据存储在某个地方,这是否会响铃?

    Exactly, Redis . 确切地说, Redis

    You can try other stores, like mongoDB or MySQL, but Redis is the fastest. 您可以尝试其他商店,如mongoDB或MySQL,但Redis是最快的。

    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. 在这个例子中,我假设你的快递应用程序和护照已经运行,并将专注于将socket.io添加到应用程序。

  • 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). Connect-redis是一个使用redis的会话存储包(如果名称不明显)。

  • 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. 在socket.request中找到的用户对象将包含登录用户的所有用户信息,您可以传递它,或者从这一点做任何您需要的用户信息。

Note : This setup will be slightly different for Socket.IO < 1.x 注意:对于Socket.IO <1.x,此设置略有不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM