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

Wes*_*Wes 5 javascript cookies session node.js express

我正在使用 express-session Node 模块来确保会话 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
}));
Run Code Online (Sandbox Code Playgroud)

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

app.get("/authenticate/:username/:password", function(req, res, next) {
    ...
});
Run Code Online (Sandbox Code Playgroud)

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

我该怎么做呢?赞赏

Pet*_*ons 5

因此,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) {
    ...
});
Run Code Online (Sandbox Code Playgroud)