我使用 Passport-Google-OAuth在我的演示站点上实现注册/登录。它工作得很好。最近几天,我试图找到如何在“GoogleStrategy”实现中访问 session 变量的解决方案。
var GoogleStrategy = require('passport-google-oauth').OAuthStrategy;
passport.use(new GoogleStrategy({
consumerKey: GOOGLE_CONSUMER_KEY,
consumerSecret: GOOGLE_CONSUMER_SECRET,
callbackURL: "http://127.0.0.1:3000/auth/google/callback"
},
function(token, tokenSecret, profile, done) {
// Is it possible to access to session variables here, eg.:
// var tmp = req.session.tmp;
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}));
我不知道这是否可能。我需要更新数据库中的现有用户,而不是创建新用户,但无法在此函数中“获取”现有用户的 _id。
最佳答案
来自文档:http://passportjs.org/guide/authorize/
验证回调中的关联
将策略的 passReqToCallback 选项设置为 true。启用此选项后,req 将作为第一个参数传递给验证回调。
passport.use(new TwitterStrategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: "http://www.example.com/auth/twitter/callback",
passReqToCallback: true
},
function(req, token, tokenSecret, profile, done) {
if (!req.user) {
// Not logged-in. Authenticate based on Twitter account.
} else {
// Logged in. Associate Twitter account with user. Preserve the login
// state by supplying the existing user after association.
// return done(null, req.user);
}
}
));
通过将 req 作为参数传递,验证回调可以使用请求的状态来定制身份验证过程,使用单个策略实例和一组路由来处理身份验证和授权。例如,如果用户已经登录,则可以关联新“连接”的帐户。也可以使用在 req 上设置的任何其他特定于应用程序的属性,包括 req.session。
关于javascript - Node.js Passport GoogleStrategy 如何访问 session 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22000453/