cookie-session

NPM Version NPM Downloads Build Status Test Coverage

Simple cookie-based session middleware.简单的基于cookie的会话中间件。

A user session can be stored in two main ways with cookies: on the server or on the client. 用户会话可以通过cookie以两种主要方式存储:在服务器上或在客户机上。This module stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.此模块将会话数据存储在cookie中的客户端上,而类似express-session的模块仅将会话标识符存储在cookie中的客户端上,并将会话数据存储在服务器上,通常存储在数据库中。

The following points can help you choose which to use:以下几点可以帮助您选择使用哪一个:

Install安装

This is a Node.js module available through the npm registry. 这是一个Node.js模块,可通过npm注册表获得。Installation is done using the npm install command:使用npm install命令完成安装:

$ npm install cookie-session

API

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.use(cookieSession({
  name: 'session',
  keys: [/* secret keys */],

  // Cookie Options
  maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))

cookieSession(options)

Create a new cookie session middleware with the provided options. 使用提供的选项创建新的cookie会话中间件。This middleware will attach the property session to req, which provides an object representing the loaded session. 该中间件将属性session附加到reqreq,它提供一个表示已加载会话的对象。This session is either a new session if no valid session was provided in the request, or a loaded session from the request.如果请求中未提供有效会话,则此会话是新会话,或者是请求中加载的会话。

The middleware will automatically add a Set-Cookie header to the response if the contents of req.session were altered. 如果req.session的内容被更改,中间件将自动向响应添加一个Set-Cookie头。Note that no Set-Cookie header will be in the response (and thus no session created for a specific user) unless there are contents in the session, so be sure to add something to req.session as soon as you have identifying information to store for the session.请注意,除非会话中有内容,否则响应中不会出现Set-Cookie标头(因此也不会为特定用户创建会话),因此请确保在您有会话的标识信息要存储后,立即向req.session添加内容。

Options选项

Cookie session accepts these properties in the options object.Cookie会话在options对象中接受这些属性。

name

The name of the cookie to set, defaults to session.要设置的cookie的名称默认为session

keys

The list of keys to use to sign & verify cookie values, or a configured Keygrip instance. 用于签名的密钥列表&;验证cookie值或已配置的Keygrip实例。Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation. Set cookies始终使用keys[0]签名,而其他键对验证有效,允许键旋转。If a Keygrip instance is provided, it can be used to change signature parameters like the algorithm of the signature.如果提供了Keygrip实例,则可以使用它更改签名参数,如签名的算法。

secret

A string which will be used as single key if keys is not provided.如果未提供键,将用作单个keys的字符串。

Cookie Options选项

Other options are passed to cookies.get() and cookies.set() allowing you to control security, domain, path, and signing among other settings.其他选项传递给cookies.get()cookies.set(),允许您在其他设置中控制安全性、域、路径和签名。

The options can also contain any of the following (for the full list, see cookies module documentation:这些选项还可以包含以下任何内容(有关完整列表,请参阅cookies模块文档):

req.session

Represents the session for the given request.表示给定请求的会话。

.isChanged

Is true if the session has been changed during the request.如果在请求过程中更改了会话,则为true

.isNew

Is true if the session is new.如果会话是新的,则为true

.isPopulated

Determine if the session has been populated with data or is empty.确定会话是否已填充数据或为空。

req.sessionOptions

Represents the session options for the current request. 表示当前请求的会话选项。These options are a shallow clone of what was provided at middleware construction and can be altered to change cookie setting behavior on a per-request basis.这些选项是中间件构造中提供的内容的简单克隆,可以根据每个请求更改cookie设置行为。

Destroying a session销毁会话

To destroy a session simply set it to null:要销毁会话,只需将其设置为null

req.session = null

Saving a session保存会话

Since the entire contents of the session is kept in a client-side cookie, the session is "saved" by writing a cookie out in a Set-Cookie response header. 由于会话的全部内容都保存在客户端cookie中,因此通过在Set-Cookie响应头中写入cookie来“保存”会话。This is done automatically if there has been a change made to the session when the Node.js response headers are being written to the client and the session was not destroyed.如果在将Node.js响应头写入客户端时对会话进行了更改,并且会话未被破坏,则会自动执行此操作。

Examples例子

Simple view counter example简单视图反例

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.set('trust proxy', 1) // trust first proxy

app.use(cookieSession({
  name: 'session',
  keys: ['key1', 'key2']
}))

app.get('/', function (req, res, next) {
  // Update views
  req.session.views = (req.session.views || 0) + 1

  // Write response
  res.end(req.session.views + ' views')
})

app.listen(3000)

Per-user sticky max age每个用户的最大寿命

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.set('trust proxy', 1) // trust first proxy

app.use(cookieSession({
  name: 'session',
  keys: ['key1', 'key2']
}))

// This allows you to set req.session.maxAge to let certain sessions这允许您设置req.session.maxAge以允许某些会话
// have a different value than the default.具有与默认值不同的值。
app.use(function (req, res, next) {
  req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge
  next()
})

// ... your logic here ...

Extending the session expiration延长会话到期时间

This module does not send a Set-Cookie header if the contents of the session have not changed. 如果会话的内容没有更改,则此模块不会发送Set-Cookie标头。This means that to extend the expiration of a session in the user's browser (in response to user activity, for example) some kind of modification to the session needs be made.这意味着要延长用户浏览器中会话的到期时间(例如,响应用户活动),需要对会话进行某种修改。

var cookieSession = require('cookie-session')
var express = require('express')

var app = express()

app.use(cookieSession({
  name: 'session',
  keys: ['key1', 'key2']
}))

// Update a value in the cookie so that the set-cookie will be sent.更新cookie中的值,以便发送设置的cookie。
// Only changes every minute so that it's not sent with every request.每分钟只更改一次,这样就不会随每个请求一起发送。
app.use(function (req, res, next) {
  req.session.nowInMinutes = Math.floor(Date.now() / 60e3)
  next()
})

// ... your logic here ...

Using a custom signature algorithm使用自定义签名算法

This example shows creating a custom Keygrip instance as the keys option to provide keys and additional signature configuration.此示例显示如何创建自定义Keygrip实例作为keys选项,以提供密钥和其他签名配置。

var cookieSession = require('cookie-session')
var express = require('express')
var Keygrip = require('keygrip')

var app = express()

app.use(cookieSession({
  name: 'session',
  keys: new Keygrip(['key1', 'key2'], 'SHA384', 'base64')
}))

// ... your logic here ...

Usage Limitations使用限制

Max Cookie Size最大Cookie大小

Because the entire session object is encoded and stored in a cookie, it is possible to exceed the maxium cookie size limits on different browsers. 因为整个会话对象都编码并存储在cookie中,所以在不同的浏览器上可能会超过最大cookie大小限制。The RFC6265 specification recommends that a browser SHOULD allowRFC6265规范建议浏览器应允许

At least 4096 bytes per cookie (as measured by the sum of the length of the cookie's name, value, and attributes)每个cookie至少4096字节(通过cookie的名称、值和属性的长度之和来衡量)

In practice this limit differs slightly across browsers. 实际上,不同浏览器的限制略有不同。See a list of browser limits here. 请参见此处的浏览器限制列表。As a rule of thumb don't exceed 4093 bytes per domain.根据经验,每个域不超过4093字节。

If your session object is large enough to exceed a browser limit when encoded, in most cases the browser will refuse to store the cookie. 如果会话对象足够大,编码时超出浏览器限制,则在大多数情况下,浏览器将拒绝存储cookie。This will cause the following requests from the browser to either a) not have any session information or b) use old session information that was small enough to not exceed the cookie limit.这将导致以下来自浏览器的请求a)没有任何会话信息,或b)使用小到不超过cookie限制的旧会话信息。

If you find your session object is hitting these limits, it is best to consider if data in your session should be loaded from a database on the server instead of transmitted to/from the browser with every request. 如果发现会话对象正在命中这些限制,最好考虑会话中的数据是否应该从服务器上的数据库加载,而不是用每个请求发送到浏览器。Or move to an alternative session strategy或者转向另一种会话策略

License许可证

MIT