【问题标题】:passportjs google oauth2 strategy护照js谷歌oauth2策略
【发布时间】:2017-12-27 20:12:33
【问题描述】:

在 PassportJS Google OAuth 策略中,由于一些奇怪的原因,当我序列化用户 id 并将其发送到 cookie 以发送到浏览器时,它不会返回 id 来反序列化它,这告诉我,因为当我console.log用户,返回undefined

passport.deserializeUser((id, done) => {
    User.findById(id).then((user, done) => {
        console.log(user);
        done(null, user);
    });
});

详细说明我的 cookie 在下面

app.use(cookieSession({
  maxAge: 24 * 60 * 60 * 1000,
  keys: 'dkfehfhgddf'
}));

【问题讨论】:

  • 您是否使用 Mongoose 从 MongoDB 中获取用户数据?
  • 是的,我愿意。使用 mongodb

标签: javascript node.js express passport.js cookie-session


【解决方案1】:

如果您使用的是 Mongoose,您的代码中出现了错误,导致了意外行为。

如果您尝试使用 findById() 函数的 Promise 版本,则必须在之后调用 .exec() 才能调度操作。此外,您还隐藏了deserializeUserdone 回调,因此它永远不会被调用。

这是它的工作原理:

passport.deserializeUser((id, done) => {
  User.findById(id).exec()
    .then(user => {
      if (user) {// user may be null
        done(null, user);
      } else {
        done(new Error("User not found"), null);
      }  
   })
   .catch(error => {
     done(error, false);
   });
});

【讨论】:

  • 感谢您的澄清。好吧,当我 console.log 将 id 返回给 mongo 时,它会从浏览器返回任何内容。因此数据库甚至没有收到 id 来查询它
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 2018-05-16
  • 2019-11-15
  • 2018-12-13
  • 2012-06-09
  • 2019-01-29
  • 2016-11-29
  • 2015-03-20
相关资源
最近更新 更多