我的应用允许用户通过PassportJS为其帐户设置多个oAuth连接。
每当我连接另一个应用程序(使用Mailchimp策略和Salesforce策略)时,Passport会将我注销(结束我的express-session
)。似乎Passport正在尝试使用我连接的每个策略的新会话登录,这根本不是我想要的。
我认为秘诀在于我使用的策略回调,即返回done()
函数:
passport.use(new MailChimpStrategy({
clientID: auth.mailchimpAuth.clientID,
clientSecret: auth.mailchimpAuth.clientSecret,
callbackURL: auth.mailchimpAuth.callback
}, function(accessToken, refreshToken, profile, done) {
process.nextTick(function() {
Chimp.findOne({'login_name': profile._json.login.login_name},
function(err, chimp) {
if (err) {
return done(err);
}
if (!chimp) {
var newChimp = new Chimp();
newChimp.login_name = profile._json.login.login_name;
newChimp.profile = profile;
newChimp.authUsers = [];
newChimp.domain = '';
newChimp.accessToken = accessToken;
newChimp.lists = {};
newChimp.save(function(err) {
if (err) {
return done(err);
} else {
return done(null, newChimp);
}
});
} else {
var newChimp = chimp;
return done(null, newChimp);
}
});
});
}));
据推测,这是因为当我使用新API进行身份验证时,我的用户正在更改Passport的内容。我可以通过检查传递给user.id
和passport.serializeuser()
的{{1}}对象来看到这一点。但是我没有在这里制作新用户 - 我只是将每个API返回的配置文件添加到我的原始用户帐户。
如何防止这种情况发生并使原始会话保持活动状态?
答案 0 :(得分:0)
想出一个解决方案(对于任何赞成这个问题的人):
我认为它与被返回的done()
有关,这是正确的。会发生什么是done()
将对象返回serializeUser()
,然后将其传递给deserializeUser()
。
所以在我的mailChimpStrategy
函数中,我添加passReqToCallback: true
,然后从回调函数访问登录用户:
passport.use(new MailChimpStrategy({
clientID: auth.mailchimpAuth.clientID,
clientSecret: auth.mailchimpAuth.clientSecret,
callbackURL: auth.mailchimpAuth.callback,
passReqToCallback: true
}, function(req, accessToken, refreshToken, profile, done) {
var tempUser = {id: req.session.passport.user}
User.findById(tempUser.id, function(err, usr){
var newChimp = new Chimp(); // Make new Mongoose Chimp object
// Do Chimp profile setting here
// Then, when done, instead of passing the Chimp profile object, I pass the user ID.
return done(null, tempUser);
})
});
完成并完成。