Javascript 会话如何在 Express.js 和 Node.js 中工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5522020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:36:48  来源:igfitidea点击:

How do sessions work in Express.js with Node.js?

javascriptnode.jssessioncookiesexpress

提问by foobar

Using Express.js, sessions are dead simple. I'm curious how they actually work though.

使用Express.js,会话非常简单。我很好奇它们实际上是如何工作的。

Does it store some cookie on the client? If so, where can I find that cookie? If required, how do I decode it?

它是否在客户端上存储了一些 cookie?如果是这样,我在哪里可以找到那个 cookie?如果需要,我该如何解码?

I basically want to be able to see if a user is logged in, even when the user is not actually on the site at the time (like how facebook knows you're logged in when you're on other sites). But I suppose to understand that I should first understand how sessions work.

我基本上希望能够查看用户是否已登录,即使该用户当时实际上并未在该网站上(例如,当您在其他网站上时,facebook 如何知道您已登录)。但我想明白我应该首先了解会话是如何工作的。

采纳答案by davin

I have never used Express.js, although according to their documentationon the subject it sounds like:

我从未使用过 Express.js,但根据他们关于该主题的文档,它听起来像:

  • Cookies are stored on the client, with a key (which the server will use to retrieve the session data) and a hash (which the server will use to make sure the cookie data hasn't been tampered with, so if you try and change a value the cookie will be invalid)

  • The session data, as opposed to some frameworks (e.g. Play Framework!) is held on the server, so the cookie is more like a placeholder for the session than a holder of actual session data.

  • From here, it looks like this session data on the server is by default held in memory, although that could be altered to whatever storage form implements the appropriate API.

  • Cookie 存储在客户端上,带有一个密钥(服务器将使用它来检索会话数据)和一个哈希值(服务器将使用它来确保 cookie 数据未被篡改,因此如果您尝试更改cookie 将无效的值)

  • 与某些框架(例如Play Framework!)相反,会话数据保存在服务器上,因此 cookie 更像是会话的占位符,而不是实际会话数据的持有者。

  • 这里看来,服务器上的会话数据默认保存在内存中,尽管可以将其更改为实现适当 API 的任何存储形式。

So if you want to check things without a specific reqrequest object, like you said, you need to just access that same storage. On the bottom of the first documentation page, it details required methods the storage needs to implement, so if you're familiar with your storage API, maybe you could execute a .getAll()if something like that exists, and loop through the session data and read whatever values you want.

因此,如果您想在没有特定req请求对象的情况下检查事物,就像您说的那样,您只需要访问相同的存储。在第一个文档页面的底部,它详细说明了存储需要实现的所需方法,所以如果你熟悉你的存储 API,也许你可以执行一个.getAll()if 类似的东西存在,并遍历会话数据并读取任何内容你想要的价值观。

回答by Waylon Flinn

Overview

概述

Express.js uses a cookie to store a session id (with an encryption signature) in the user's browser and then, on subsequent requests, uses the value of that cookie to retrieve session information stored on the server. This server side storage can be a memory store (default) or any other store which implements the required methods (like connect-redis).

Express.js 使用 cookie 在用户浏览器中存储会话 ID(带有加密签名),然后在后续请求中使用该 cookie 的值来检索存储在服务器上的会话信息。此服务器端存储可以是内存存储(默认)或任何其他实现所需方法的存储(如connect-redis)。

Details

细节

Express.js/Connect creates a 24-character Base64string using utils.uid(24)and stores it in req.sessionID. This string is then used as the value in a cookie.

Express.js/Connect使用.js 创建一个 24 个字符的Base64字符串utils.uid(24)并将其存储在req.sessionID. 然后将此字符串用作 cookie 中的值。

Client Side

客户端

Signed cookies are always used for sessions, so the cookie value will have the following format.

签名 cookie 始终用于会话,因此 cookie 值将具有以下格式。

[sid].[signature]

Where [sid] is the sessionID and [signature] is generated by signing [sid] using the secret key provided when initializing the session middleware. The signing step is done to prevent tampering. It should be computationally infeasable to modify [sid] and then recreate [signature] without knowledge of the secret key used. The session cookie is still vulnerable to theft and reuse, if no modification of [sid] is required.

其中 [sid] 是 sessionID,而 [signature] 是通过使用初始化会话中间件时提供的密钥对 [sid] 进行签名来生成的。签名步骤是为了防止篡改。在不知道所使用的密钥的情况下修改 [sid] 然后重新创建 [签名] 在计算上应该是不可行的。如果不需要修改 [sid],会话 cookie 仍然容易被盗和重用。

The name for this cookie is

这个cookie的名字是

connect.sid

Server Side

服务器端

If a handler occurs after the cookieParserand sessionmiddleware it will have access to the variable req.cookies. This contains a JSON object whose keys are the cookie keys and values are the cookie values. This will contain a key named connect.sidand its value will be the signed session identifier.

如果处理程序出现在cookieParsersession中间件之后,它将可以访问变量req.cookies。这包含一个 JSON 对象,其键是 cookie 键,值是 cookie 值。这将包含一个名为的密钥connect.sid,其值将是签名的会话标识符。

Here's an example of how to set up a route that will check for the existence of the session cookie on every request and print its value to the console.

这是一个如何设置路由的示例,该路由将检查每个请求上是否存在会话 cookie 并将其值打印到控制台。

app.get("/*", function(req, res, next) {

    if(typeof req.cookies['connect.sid'] !== 'undefined') {
        console.log(req.cookies['connect.sid']);
    }

    next(); // Call the next middleware
});

You'll also need to make sure the router (app.use(app.router)) is included after cookieParserand sessionin your configure section.

您还需要确保在配置部分app.use(app.router)之后cookieParsersession中包含路由器 ( ) 。

The following is an example of the data stored internally by Express.js/Connect.

以下是 Express.js/Connect 内部存储的数据示例。

{
  "lastAccess": 1343846924959,
  "cookie": {
    "originalMaxAge": 172800000,
    "expires": "2012-08-03T18:48:45.144Z",
    "httpOnly": true,
    "path": "/"
  },
  "user": { 
    "name":"waylon",
    "status":"pro"
  }
}

The userfield is custom. Everything else is part of session management.

user字段是自定义的。其他一切都是会话管理的一部分。

The example is from Express 2.5.

该示例来自 Express 2.5。

回答by yojimbo87

I'm curious how they actually work though.

我很好奇它们实际上是如何工作的。

Try to look at thisanswer and wikistuff.

试着看看这个答案和维基的东西。

Does it store some cookie on the client?

它是否在客户端上存储了一些 cookie?

Yes, it's usually a cookie with assigned session ID, which should be signed with a secret in order to prevent forgery.

是的,它通常是一个带有指定会话 ID 的 cookie,应该用秘密签名以防止伪造。

If so, where can I find that cookie? If required, how do I decode it?

如果是这样,我在哪里可以找到那个 cookie?如果需要,我该如何解码?

You shouldn't mess with a session cookie on the client side. If you want to work with sessions on the server side you should check out related express.jsand connectdocs.

您不应该在客户端弄乱会话 cookie。如果你想在服务器端使用会话,你应该查看相关的express.js连接文档。

回答by abernier

In addition to already excellent answers, here are 2 diagrams I've created to explain Express sessions, their link with cookies and store :

除了已经很好的答案之外,我还创建了 2 个图表来解释 Express 会话,它们与 cookie 和 store 的链接:

  • chocolate cookie: chocolate
  • strawberry cookie: strawberry
  • 巧克力曲奇: 巧克力
  • 草莓饼干: 草莓