在Passport策略callback中获取请求对象

所以这里是我的passport-facebook策略configuration:

passport.use(new FacebookStrategy({ clientID: ".....", clientSecret: ".....", callbackURL: "http://localhost:1337/register/facebook/callback", }, facebookVerificationHandler )); 

这里是facebookVerificationHandler:

 var facebookVerificationHandler = function (accessToken, refreshToken, profile, done) { process.nextTick(function () { ....... }); }; 

有没有办法访问facebookVerificationHandler中的请求对象?

用户通过LocalStrategy注册到我的网站,然后他们将能够添加他们的社交帐户,并将这些帐户与他们的本地帐户相关联。 当上面的callback被调用时,当前login的用户在req.user中已经可用,所以我需要访问req来将用户和facebook账户关联起来。

这是实施它的正确方法,还是应该考虑另一种方法?

谢谢。

出于这个原因,而不是在应用程序启动时设置策略,通常在有请求时设置策略。 例如:

 app.get( '/facebook/login' ,passport_setup_strategy() ,passport.authenticate() ,redirect_home() ); var isStrategySetup = false; var passport_setup_strategy = function(){ return function(req, res, next){ if(!isStrategySetup){ passport.use(new FacebookStrategy({ clientID: ".....", clientSecret: ".....", callbackURL: "http://localhost:1337/register/facebook/callback", }, function (accessToken, refreshToken, profile, done) { process.nextTick(function () { // here you can access 'req' ....... }); } )); isStrategySetup = true; } next(); }; } 

使用这个,您将有权访问您的validation处理程序中的请求。

有一个passReqToCallback选项,请参阅此页面的底部以获得详细信息: http : passReqToCallback

尝试这个。

 exports.facebookStrategy = new FacebookStrategy({ clientID: '.....', clientSecret: '...', 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); }); }); } }); } ); 

用户是mongoose模型,我将用户保存在数据库中。