简体   繁体   English

在cookie解析器和会话中秘密设置在express.js中存储相同的东西吗?

[英]Is secret set in cookie parser and session store the same thing in express.js?

The authentication example provided by Node.js uses the following piece of code: Node.js提供的身份验证示例使用以下代码:

app.use(express.cookieParser('shhhh, very secret'));
app.use(express.session());

However, the documentation of express.js session uses the following: 但是, express.js会话的文档使用以下内容:

app.use(cookieParser())
app.use(session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }}))

This is confusing. 这令人困惑。 Are both secrets the same? 两个秘密都一样吗? Which method should I use if I store my sessions in a database? 如果我将会话存储在数据库中,我应该使用哪种方法?

The express 3.5.x versions should still use the connect some of the libraries which base on the connect module . 快速3.5.x版本仍然应该使用连接一些基于连接模块的库。

The cookieParser middleware cookieParser中间件

connect()
  .use(connect.cookieParser('optional secret string'))
  .use(function(req, res, next){
    res.end(JSON.stringify(req.cookies));
  })

Nex there is session middleware which by default uses the in-memory storage, if you want to scale your application use Redis, Mongo or any other database for memory storage: Nex有会话中间件,默认情况下使用内存存储,如果要扩展应用程序,请使用Redis,Mongo或任何其他数据库进行内存存储:

connect()
  .use(connect.cookieParser())
  .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }}))

Reading more about the connect's session middleware, there are two lines to answer your question. 阅读有关connect的会话中间件的更多信息,有两行可以回答您的问题。 ( http://www.senchalabs.org/connect/session.html ) http://www.senchalabs.org/connect/session.html

// backwards compatibility for signed cookies
// req.secret is passed from the cookie parser middleware
var secret = options.secret || req.secret;

// ensure secret is available or bail
if (!secret) throw new Error('`secret` option required for sessions');

The secret session cookie is signed with this secret to prevent tampering. 秘密会话cookie使用此秘密签名以防止篡改。 So basically these are same, but when you have added the session support remove the options in cookieParser and use only the option settings in session middleware. 所以基本上这些是相同的,但是当你添加了会话支持时,删除cookieParser中的选项并仅使用会话中间件中的选项设置。

Also be aware the Express 4.x version brings some of the middleware changes! 另请注意Express 4.x版本带来了一些中间件更改!

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

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