node.js - IsAuthenticated 不能作为使用带有本地护照的 nodejs 的函数工作
问题描述
我是 node js 的初学者,我正在尝试检查用户在注册后是否经过身份验证。
我正在使用护照、护照本地和护照本地猫鼬将用户保存在 mongoDB 数据库中。
这是用户注册的方式:
app.post("/register", function (req, res) {
const username = req.body.username;
const password = req.body.password;
User.register({username: username}, password, function (err, user) {
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/drive");
});
}
});
});
这就是我试图检查用户是否经过身份验证的方式:
app.get("/drive", function (req, res) {
if (req.isAuthenticated()) {
res.render("drive");
} else {
res.redirect("/login");
}
});
如果我使用isAuthenticated()作为函数调用,则此逻辑将不起作用,并且我将始终重定向到登录页面,如果我使用isAuthenticated(不是函数调用),则此逻辑将起作用。
我不明白这两者之间有什么区别(在护照包裹的情况下)以及为什么一个有效而另一个无效。
解决方案
设法解决了这个问题,这是一个非常简单的问题。
当我声明我的会话选项时:
app.use(session({
secret: 'Our little secret.',
resave: false,
saveUninitialized: false,
cookie: {secure: true}
}))
我正在使用cookie: {secure: true}
,并且由于我在没有 HTTPS 的本地环境中工作,所以一旦我进行身份验证,我就会被取消身份验证,因为应该生成的 cookie 只能在 HTTPS 下工作。
解决方案是将cookie选项设置为false并调用isAuthenticated()。
推荐阅读
- typo3 - Typo3 8.7 Fluid 渲染为空,如果我将扩展放入静态模板,为什么?
- hibernate - 在 Hibernate 的单个查询中获取相关实体
- c# - 如何使用从 C# 调用的 PowerShell 进行降序排序
- protractor - 如果 BeforeAll 失败,则量角器文件中的所有测试都失败
- azure-devops - 正确的 VSS.register() 返回语法
- ruby-on-rails - 如何链接_以使用其 ID 编辑特定帖子?我需要硬连线ID
- google-apps-script - 如何与其他 Google Cloud 项目共享 Google Apps 脚本插件的 Google API 授权?
- firebase - 如何在firebase中附加数据?
- bash - 关于内存,将输出读入数组和将输出读入 while 循环之间有区别吗?
- xml - LiquidXML DataBinding 在导出为 XML 字符串时抑制 NodeType