【问题标题】:IsAuthenticated not working as a function using nodejs with passport-localIsAuthenticated 不能作为使用带有本地护照的 nodejs 的函数工作
【发布时间】:2020-10-25 21:19:36
【问题描述】:

我是 node js 的初学者,我正在尝试检查用户在注册后是否经过身份验证。

我正在使用 passport、passport-local 和 passport-local-mongoose 将用户保存在 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.js express passport.js passport-local


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 2012-12-20
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2019-08-12
      相关资源
      最近更新 更多