gpt4 book ai didi

javascript - Express js session--只为登录用户创建

转载 作者:行者123 更新时间:2023-11-29 21:55:28 27 4
gpt4 key购买 nike

我正在为安全 session cookie 使用 express-session Node 模块。

// 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
}));

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

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

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

我该怎么做?赞赏

最佳答案

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

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

但要明确回答您的问题,即使这种方法最终不可行,您也可以将 session 从全局中间件转换为仅添加到该路由的中间件:

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

关于javascript - Express js session--只为登录用户创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26633397/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com