Express js会话 – 仅为login用户创build

我正在使用快速会话节点模块来保护会话cookie。

// Secure session cookie that ensures certain requests require an active session app.use(expressSession({ secret: "wouldn'tyouliketoknow", cookie: { maxAge: new Date(Date.now() + 3600), // 1 hour httpOnly: true, secure: true, // Requires https connection }, // Stores sessions in Mongo DB store: new MongoStore({ host: mongo, port: 27017, db: 'iod', collection: 'sessions' }), // Gets rid of the annoying deprecated messages resave: false, saveUninitialized: false })); 

无论请求是什么,这都会创build一个安全的会话cookie。 我只想为用户成功login时创build一个会话,例如这样的请求:

 app.get("/authenticate/:username/:password", function(req, res, next) { ... }); 

基本上我只想在获取处理程序中成功满足条件时创build的cookie。

我将如何去做呢? 赞赏

所以Express会按照你添加到app的顺序运行中间件。 所以这里实现你的目标的正常策略是确保你定义:

  1. 所有静态和非会话路线(图像,字体,CSS,营销页面等)
  2. 会话中间件
  3. 所有应用路由。 你不能只在loginpath上这样做,因为你需要在所有需要会话和authentication用户的应用程序path上强制login用户。

但是,具体来说,即使这种方法不是最终可行的,但是您可以将会话从全局中间件转换为仅添加到该一个路由的中间件:

 var sessionMW = expressSession({ secret: "wouldn'tyouliketoknow", cookie: { maxAge: new Date(Date.now() + 3600), // 1 hour httpOnly: true, secure: true, // Requires https connection }, // Stores sessions in Mongo DB store: new MongoStore({ host: mongo, port: 27017, db: 'iod', collection: 'sessions' }), // Gets rid of the annoying deprecated messages resave: false, saveUninitialized: false }); app.get("/authenticate/:username/:password", sessionMW, function(req, res, next) { ... });