学习Nodejs有一段时间了,一直没有去整理关于Cookie和Session的机制,今天静下心去码码字。
首先引用这几个模块
var cookieSession = require('cookie-session')
var session = require('express-session'); //如果要使用session,需要包含这个模块
var cookieParser = require('cookie-parser'); //如果要使用cookie,需要包含这个模块
关于Cookie-Session
var cookieSession = require('cookie-session')
Create a new cookie session middleware with the provided options. This middleware will attach the property session to req, which
provides an object representing the loaded session. This session is
either a new session if no valid session was provided in the request,
or a loaded session from the request.
也就是说:使用提供的方式创建一个cookie session 中间件。这个中间件将作为一个属性被添加到req(请求头)中。如果请求中并不含有合法的session,那么将创建一个新的session;如果已经有了session,就加载这个已知session。
The middleware will automatically add a Set-Cookie header to the
response if the contents of req.session were altered. 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被改变了。注意Set-Cookie头将被放在响应中除非他们是session的内容。所以如果你已经确定要将一些内容存储在会话中,一定要尽快的将其加入到req.session中。
Cookie Session (Options)
name 需要设置的cookie的名字
keys 秘钥 使用秘钥列表去签署/验证cookie的值。一般我们使用'keys[0]'去签署一个cookie
secret 如果没有提供秘钥keys 我们可以使用一个字符串来作为单个key
其他的Options 通过 'cookies.get()'和'cookies.set()'来实现,例如控制security, domain, path,和signing 等等
'maxAge' 从'Date.now()'起计时,cookie的最大保存时间
'expires' 到期日 指定一个cookie的到期时间(默认放在会话的末尾)
'path' 字符串 指定cookie的路径 (默认是/)
'domain' cookie的域名 没有默认值
'secure' 一个布尔属性 指定是否用https协议(如果为false 就是http,如果是true,就是https)
'secureProxy' 布尔属性 指定cookie是否只在https环境下发送。(如果你处理的ssl并不在node进程中,可以使用这个)
'httpOnly' 布尔属性 指定cookie只在http(s)环境下发送,并且不能在客户端的JavaScript中调用(默认是true)
[<script>document.write(document.cookie);</script> 关于JS调用cookie的方法]
'signed' 布尔属性 指定一个cookie是否被签署(关于signed cookie的问题 Stackflow上的解答是这样的:The cookie will still be visible, but it has a signature, so it can detect if the client modified the cookie. 参见(http://stackoverflow.com/questions/11897965/what-are-signed-cookies-in-connect-expressjs)
默认是ture属性。如果是ture,其他的具有相同name的cookie将附带发送一个.sig的后缀名的文件 (这是一个27比特的base64 SHA1加密的值,展示的内容是cookie-name=cookie-value的哈希值通过与第一个Keygrip的值[关于keygrip 参见'https://www.npmjs.com/package/keygrip' Keygrip is a node.js module for signing and verifying data (such as cookies or URLs) through a rotating credential system, in which new server keys can be added and old ones removed regularly, without invalidating client credentials.])这个签署的秘钥用于检测下一个收到的cookie是否被篡改
'overwrite' 布尔属性 用于指定是否覆盖之前设定的同名cookie值(默认为true) 如果是true属性,在相同的请求中的同名cookie(不考虑path和domain)在设定的时候将忽略Set-Cookie头
req.session (Options)
Represents the session for the given request.
'.isChanged' 如果在请求中改变了session 就为true
'.isNew' 如果会话是新的 true
'.isPopulated' 判断session中是否被填充了数据或者是空
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.use(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)
关于 Cookie-Parser
Parse Cookie header and populate req.cookies with an object keyed by
the cookie names. Optionally you may enable signed cookie support by
passing a secret string, which assigns req.secret so it may be used by
other middleware.
解析Cookie 头 并通过cookie名称键入一个对象填充req.cookies。可选的情况下你可以通过一个secret 字符串来传递签署的cookie,这样就可以被其他的中间件调用了。
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
'cookieParser(secret, options)'
secret a string or array used for signing cookies. This is optional and if not specified, will not parse signed cookies. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order.
options an object that is passed to cookie.parse as the second option. See cookie for more information.
decode a function to decode the value of the cookie
cookieParser.JSONCookie(str)
Parse a cookie value as a JSON cookie. This will return the parsed JSON value if it was a JSON cookie, otherwise it will return the passed value.
cookieParser.JSONCookies(cookies)
Given an object, this will iterate over the keys and call JSONCookie on each value. This will return the same object passed in.
cookieParser.signedCookie(str, secret)
Parse a cookie value as a signed cookie. This will return the parsed unsigned value if it was a signed cookie and the signature was valid, otherwise it will return the passed value.
The secret argument can be an array or string. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order.
cookieParser.signedCookies(cookies, secret)
Given an object, this will iterate over the keys and check if any value is a signed cookie. If it is a signed cookie and the signature is valid, the key will be deleted from the object and added to the new object that is returned.
The secret argument can be an array or string. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order.
Example
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8080)
// curl command that sends an HTTP request with two cookies
// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"