繁体   English   中英

Node.js Passport GoogleStrategy如何访问会话数据

[英]Node.js Passport GoogleStrategy how to access session data

我使用Passport-Google-OAuth在演示站点上实现注册/登录。 效果很好。 最近几天,我尝试找到一种解决方案,该解决方案如何在“ GoogleStrategy”实现中访问会话变量。

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将作为第一个参数传递给verify回调。

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作为参数传递后,verify回调可以使用请求的状态来定制身份验证过程,使用单个策略实例和一组路由来处理身份验证和授权。 例如,如果用户已经登录,则可以关联新的“已连接”帐户。 也可以使用在req上设置的任何其他特定于应用程序的属性,包括req.session。

尝试添加passReqToCallback:true,它应该将req对象传递到您的回调中,然后将req对象作为回调中的第一个参数添加,例如,passport.use(new GoogleStrategy({passReqToCallback:true,ConsumerKey:…},function(req,令牌...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM