【问题标题】:Passport.js: no req.user stored on the sessionPassport.js:会话中没有存储 req.user
【发布时间】:2018-07-26 03:21:54
【问题描述】:

我在使用 Passport.js 和 express-session 时遇到问题。当我尝试登录时,请求就会挂起。我从 cookie-session 而不是 express-session 开始,并且使用 Google 和 Facebook 策略进行身份验证都没有问题。由于某种原因,serializeUser 和 deserializeUser 函数没有被调用,因此没有用户存储在 req 对象上。

我的代码如下。

index.js

    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(cookieParser());
    app.use(session({
       secret: sessionSecret,
       resave: false,
       saveUninitialized: false
    }));
    app.use(passport.initialize());
    app.use(passport.session());

路线

    router.get('/google', passport.authenticate('google', {
       scope: ['profile', 'email']
    }));

    router.get('/google/callback', passport.authenticate('google', {
       successRedirect: '/',
       failureRedirect: '/login'
    }));

护照设置

   passport.serializeUser((user, done) => {
     done(null, user.id);
   });

   passport.deserializeUser((id, done) => {
     User.findById(id, (e, user) => {        
     done(e, user);
   });
   });

   passport.use(new GoogleStrategy({
      clientID: googleClientID,
      clientSecret: googleClientSecret,
      callbackURL: '/auth/google/callback',
      proxy: true
   }, async (accessToken, refreshToken, profile, done) => {
   try {
        //Does email exist in DB?
        const existingUser = await User.findOne({ 
        email: profile.emails[0].value,
       });

    if(existingUser) {
        //If email exists, is the profile id same as one in db?
        if(existingUser.googleId === profile.id) return done(null, 
        existingUser);

        //If email exists but no google id, set one
        if(!existingUser.googleId) {
            const user = await User.findOneAndUpdate({ 
                email: profile.emails[0].value 
            }, {
                $set: {
                    googleId: profile.id
                }
            }, {
                new: true
            });
            return done(null, user);
        }            
    }

    const newUser = await new User({
        email: profile.emails[0].value,
        googleId: profile.id
    }).save();
    done(null, newUser);

} catch (e) {
    console.log(e);
}
}));

【问题讨论】:

    标签: node.js passport.js passport-google-oauth


    【解决方案1】:

    现在解决了这个问题。我需要一个与我的 MongoDB 数据库断开连接的种子文件。这显然会扰乱用户查找。

    【讨论】:

      猜你喜欢
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 2022-08-06
      • 2012-10-08
      • 1970-01-01
      • 2021-04-22
      • 2013-04-28
      • 2015-07-18
      相关资源
      最近更新 更多