Nodejs测试身份验证,但在浏览器中获取空白屏幕

时间:2018-04-18 22:55:09

标签: node.js passport.js

我在我的应用程序中启用了Cookie,然后基本上告诉passport在我的身份验证中使用了Cookie,从而完成了我的身份验证流程。

为了测试这一点,我在我的应用程序中添加了一个新的路由处理程序,其唯一目的是检查这个req.user属性。

这是我的services / passport.js文件:

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const mongoose = require('mongoose');
const keys = require('../config/keys');

const User = mongoose.model('users');

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

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

// passport.use() is a generic register to make Passport
// aware of new strategy
// creates a new instance to authenticate users
passport.use(
  new GoogleStrategy(
    {
      clientID: keys.googleClientID,
      clientSecret: keys.googleClientSecret,
      callbackURL: '/auth/google/callback'
    },
    (accessToken, refreshToken, profile, done) => {
      User.findOne({ googleId: profile.id }).then(existingUser => {
        if (existingUser) {
          // we already have a record with given profile id
        } else {
          // we dont have a user record with this id, make a new record
          done(null, existingUser);
          new User({ googleId: profile.id })
            .save()
            .then(user => done(null, user));
        }
      });
    }
  )
);

数据传递给passport,从cookie数据中提取id。然后将id传递给我的deserializeUser函数,我将id转换为用户模型实例,然后整个目标是从deserializeUser返回的用户模型实例{1}}作为req.user添加到请求对象中,因此上面提到的新路由处理程序有一个检查req.user的工作。

所以在我的routes / authRoutes.js中:

const passport = require('passport');

module.exports = app => {
  app.get(
    '/auth/google',
    passport.authenticate('google', {
      scope: ['profile', 'email']
    })
  );

  app.get('/auth/google/callback', passport.authenticate('google'));

  app.get('/api/current_user', (req, res) => {
    res.send(req.user);
  });
};

所以这应该测试一个已经经历过理论上的OAuth流程的人现在可以重新登录,我们可以验证同一个用户。

所以预期的行为是我将再次访问OAuth流程,访问localhost:5000/auth/google然后在localhost:5000/api/current_user中打开一个单独的浏览器,并能够看到该用户的MongoDB记录为{ {1}}在浏览器中,但我的命令行终端或其他任何地方都有一个空白页面没有错误。

这可能是什么问题?

1 个答案:

答案 0 :(得分:1)

你在if语句中注意到了一个小缺陷:

 if (existingUser) {
       // we already have a record with given profile id
 } else {
      // we dont have a user record with this id, make a new record
      done(null, existingUser);
      new User({ googleId: profile.id })
         .save()
         .then(user => done(null, user));
 }

应该是:

 if (existingUser) {
       // we already have a record with given profile id
       done(null, existingUser);
 } else {
      // we dont have a user record with this id, make a new record

      new User({ googleId: profile.id })
         .save()
         .then(user => done(null, user));
 }
相关问题