简体   繁体   中英

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:

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

However, the documentation of express.js session uses the following:

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 .

The cookieParser middleware

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:

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. ( 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. 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.

Also be aware the Express 4.x version brings some of the middleware changes!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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