passportJS:req.user 返回未定义

passportJS: req.user is returning undefined

我有简单的 passport-facebook 和 google oauth 应用程序,它可以工作,但问题是它没有正确序列化用户,我猜是因为当我登录 req.user 它 returns 未定义。这是我的 facebook oauth

代码
passport.serializeUser((user,done)=>{
  done(null,user.id)
})
passport.deserializeUser((id,done)=>{
   const user = User.findById(id)
   done(null, user)
})
 passport.use(new FacebookStrategy({
    clientID: process.env.FB_CLIENT_ID,
    clientSecret: process.env.FB_CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/facebook/callback"
  },
  async (accessToken, refreshToken, profile, done) => {
  const user = await User.findOne({ userId: profile.id })
  if(user){
    console.log('existing user '+ user)
    return done(null,user)
  }else{
   const newuser = User.create({ username: profile.displayName,userId: profile.id });
   console.log(newuser.toString())
   done(null,newuser)
   }
 }))

这是 passport-google-oauth2

passport.serializeUser((user,done)=>{
   done(null,user.id)
})
passport.deserializeUser((id,done)=>{
    const user = User.findById(id)
    done(null, user)
 })
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/google/callback"
  },
  async (accessToken, refreshToken, profile, done) => {
     const user =await User.findOne({ userId: profile.id })
       if(user){
         console.log('existing user '+ user )
         return done(null,user)
       }else{
         const newuser = User.create({ username: profile.displayName,userId: 
 profile.id });
   console.log(newuser)
   done(null,newuser)
  }

}))

这里是路由配置

router.get('/facebook', passportFacebook.authenticate('facebook'));

router.get('/facebook/callback',passportFacebook.authenticate('facebook', { failureRedirect: '/auth/login' }),
 function(req, res) {
  res.redirect('/');
 });
 router.get('/google',
  passportGoogle.authenticate('google', { scope: 'profile' }));
  router.get('/google/callback',passportGoogle.authenticate('google', { 
  failureRedirect: '/auth/login' }),
  function(req, res) {
   res.redirect('/');
 });

这段代码有什么问题?

问题是您没有 await for user in deserializeUser.

const user = User.findById(id)

您需要使用 thenawait 来自 User.findById 的结果。所以你的 deserializeUser 代码应该是

passport.deserializeUser(async (id,done) => {
    const user = await User.findById(id)
    done(null, user)
 })