简体   繁体   English

Node.js:处理多个会话

[英]Node.js: take care of multiple sessions

I'm working on a quite simple Node.js server. 我正在一个非常简单的Node.js服务器上工作。 The users authenticate via a plain username/password form and the server - after checking a db - grants or refuses the access to the other pages. 用户通过简单的用户名/密码形式进行身份验证,并且服务器在检查数据库后会授予或拒绝对其他页面的访问。

To keep track of what each user's doing I'm going to generate a UUID to send on login. 为了跟踪每个用户的操作,我将生成一个UUID并在登录时发送。 When a client asks or sends anything to the server it will include this UUID so the server will know who is the user. 当客户端询问或向服务器发送任何内容时,它将包含此UUID,以便服务器知道谁是用户。

The questions are about the life-cycle of these UUIDs: 问题与这些UUID的生命周期有关:

  • when I must remove a UUID from my local array? 什么时候必须从本地阵列中删除UUID? Ie when the user "disconnects", I guess if it explicitely logout or after a timeout of inactivity. 即当用户“断开连接”时,我猜它是否显式注销或在闲置超时之后。 I don't want to disconnect if he puts in standby his smartphone for a while. 如果他让智能手机待机一会儿,我不想断开连接。

  • if the user reloads the page when his session is still alive, I want to avoid a new login: I need a way to understand the connection is from the same user. 如果用户在会话仍处于活动状态时重新加载页面,则我希望避免重新登录:我需要一种方法来理解该连接来自同一用户。 How would you achieve this? 您将如何实现?

What I would do is use JWT. 我要做的是使用JWT。 I would ask user to login using username and password and then issue them a JWT with payload containing the user's identifier (username or id) and with a set expiry which represents the max inactivity time allowed (depends on your business logic), say 5hrs. 我会要求用户使用用户名和密码登录,然后向他们发出一个JWT,其JWT包含用户标识符(用户名或ID)的有效载荷,并具有一个设置的到期时间,该到期时间表示允许的最长不活动时间(取决于您的业务逻辑),例如5小时。 I can also contain last logout date etc. 我还可以包含上次登出日期等。

Now user sends this JWT in his header whenever he's making requests to your services, you can decode that token and check if user logged out (tokens last logout time is less than the user's logout time). 现在,无论何时用户向您的服务发出请求,用户都会在其标头中发送此JWT,您可以解码该令牌并检查用户是否注销(令牌的最后注销时间小于用户的注销时间)。

You can keep track of various things. 您可以跟踪各种事情。

There may be other ways also, using sessions. 使用会话可能还有其他方法。

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

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