首页 > 解决方案 > 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(不是函数调用),则此逻辑将起作用。

我不明白这两者之间有什么区别(在护照包裹的情况下)以及为什么一个有效而另一个无效。

标签: node.jsexpresspassport.jspassport-local

解决方案


设法解决了这个问题,这是一个非常简单的问题。

当我声明我的会话选项时:

app.use(session({
  secret: 'Our little secret.',
  resave: false,
  saveUninitialized: false,
  cookie: {secure: true}
}))

我正在使用cookie: {secure: true},并且由于我在没有 HTTPS 的本地环境中工作,所以一旦我进行身份验证,我就会被取消身份验证,因为应该生成的 cookie 只能在 HTTPS 下工作。

解决方案是将cookie选项设置为false并调用isAuthenticated()


推荐阅读