10

在Facebook上为nodejs通行证身份验证回调时,如何获取回调中的req对象?从回调函数中Passport-Facebook访问请求对象

passport.use(new FacebookStrategy({ 
    clientID: 123456789, 
    clientSecret: 'SECRET', 
    callbackURL: "http://example.com/login/facebook/callback" 
    }, 
    function(accessToken, refreshToken, profile, done){ 
    // Is there any way to get the req object in here? 
    } 
)); 

回答

15

设置passReqToCallback选项,所以:

passport.use(new LocalStrategy({ passReqToCallback: true }, 
    function(req, username, password, done) { 
    User.findOne({ username: username }, function (err, user) { 
     if (err) { return done(err); } 
     if (!user) { return done(null, false); } 
     if (!user.verifyPassword(password)) { 
     req.flash('error', 'Your password is too long'); 
     req.flash('error', 'Also, it is too short!!!'); 
     return done(null, false); 
     } 
     return done(null, user); 
    }); 
    } 
)); 

req变得验证回调

的第一个参数按https://github.com/jaredhanson/passport/issues/39

+1

这也适用于我与facebook身份验证。 – TulioPa 2013-11-12 03:56:00

+0

谢谢!这是一个很大的帮助。 – Tyguy7 2015-04-14 15:26:17

5

我回答是否为时已晚,但我认为我的解决方案更好,更传统。 在官方文档here。有一节“协会确认回调”,其中提到,如果我们的战略的passReqToCallback选项设置为,这使REQ,它将作为第一个参数验证传递回电话。

所以我FacebookStrategy现在看起来像:

var User = require('../models/UserModel.js'); 
var FacebookStrategy = require('passport-facebook').Strategy; 

exports.facebookStrategy = new FacebookStrategy({ 
     clientID: 'REPLACE_IT_WITH_CLIENT_ID', 
     clientSecret: 'REPLACE_IT_WITH_CLIENT_SECRET', 
     callbackURL: 'http://localhost:3000/auth/facebook/callback', 
     passReqToCallback: true 
    },function(req,accessToken,refreshToken,profile,done){ 
     User.findOne({ 
       'facebook.id' : profile.id 
      },function(err,user){ 
      if(err){ 
       done(err); 
      } 
      if(user){ 
       req.login(user,function(err){ 
        if(err){ 
         return next(err); 
        } 
        return done(null,user); 
       }); 
      }else{ 
       var newUser = new User(); 
       newUser.facebook.id = profile.id; 
       newUser.facebook.name = profile.displayName; 
       newUser.facebook.token = profile.token; 
       newUser.save(function(err){ 
        if(err){ 
         throw(err); 
        } 
        req.login(newUser,function(err){ 
         if(err){ 
          return next(err); 
         } 
         return done(null,newUser); 
        }); 
       }); 
      } 
     }); 
    } 
); 

在我的代码示例我已经增加了一些逻辑保存在数据库中的会话保存用户信息的用户信息和。我认为这可能对人们有帮助。

req.user给出存储在护照会话中的用户信息。

+0

谢谢!这是一个很大的帮助。 – Tyguy7 2015-04-14 15:26:20

相关问题