Express js会话——仅为登录用户创建

Express js session-- Create only for logged in users

本文关键字:登录 用户 创建 js 会话 Express      更新时间:2023-09-26

我正在使用快速会话节点模块进行安全会话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
}));

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

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

基本上,我希望只有在get处理程序中成功满足条件时才能创建cookie。

我该怎么做呢?赞赏

因此express将按照您将中间件添加到app的顺序运行中间件。因此,实现目标的正常策略是确保您定义:

  1. 所有静态和非会话路由(图像、字体、css、营销页面等)
  2. 会话中间件
  3. 所有应用程序路由。您不能只在登录路由上使用它,因为您需要在所有需要会话和经过身份验证的用户的应用程序路由上强制使用登录用户

但具体来说,为了回答您的问题,即使这种方法最终不可行,您只需将会话从全局中间件转换为仅添加到该路径的中间件:

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) {
    ...
});