express - 来自快速会话的会话不会通过请求持续存在
问题描述
我正在使用express-session
并尝试使用自定义中间件实现受保护的路由。
[注意:我目前正在将我的会话存储在内存中]
app.use(
session({
secret: "f4z4gs$Gcg",
cookie: { maxAge: 300000000, secure: true },
saveUninitialized: false,
resave: false,
store,
})
);
// MIDDLEWARE
function ensureAuthenticated(req, res, next) {
console.log(req.session) // This doesn't show the user and authenticated properties created in the POST login request
if (req.session.authenticated) {
return next();
} else {
res.status(403).json({ msg: "You're not authorized to view this page" });
}
};
app.post("/login", (req, res) => {
const { username, password } = req.body;
db.users.findByUsername(username, (err, user) => {
if (user) {
if (user.password === password) {
// Add your authenticated property below:
req.session.authenticated = true;
// Add the user object below:
req.session.user = {
username,
password,
};
// Send the session back to the client below:
res.json(req.session); // Properties show up here
} else {
res.status(403).json({ msg: "Bad Credentials" });
}
} else {
res.status(403).json({ msg: "No user found!" });
}
});
});
// PROTECTED ROUTE
app.get("/protected", ensureAuthenticated, (req, res) => {
res.render("profile");
});
用户成功登录后,我尝试将两个属性添加到req.session
:authenticated
和user
对象中。但是,一旦我登录并尝试使用/protected
中间件访问,我的会话属性就不会持续存在(没有user
或authenticated
属性)。我错过了什么吗?
解决方案
尝试在 cookie 对象中将 secure 设置为 false。如果您希望它是 httpOnly,那么只需将 httpOnly 设置为 true。
推荐阅读
- material-ui - Uno 材质底部导航栏
- delphi - 使表单无效会使其中的所有控件失效吗?
- bash - 任意深度的嵌套自动完成
- sql-server - 如何解决 SQL Server 中的排序规则冲突?
- git - 如何使用换行符“\n”从 Sourcetree 中删除不存在的文件?
- java - 将 ByteArrayInputStream 转换为文件而不保存到磁盘
- angular - 将 Auth0 不记名令牌添加到 Angular HttpInterceptor
- java - Maven Java SpringCould not find artifact org.vaadin.crudui:crudui:pom:4.3.0 in central
- deep-learning - 如何通过单个操作合并两个 torch.utils.data 数据加载器
- python - 如何将 Teradata QUALIFY 关键字添加到 SQLAlchemy 核心语句的末尾?