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

San*_*kic 2 javascript node.js oauth-2.0 passport.js

我使用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);
    });
}));
Run Code Online (Sandbox Code Playgroud)

我不知道这是否可能.我需要更新数据库中的现有用户,而不是创建新用户,但不能在此功能中"获取"现有用户的_id.

小智 5

来自文档: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);
    }
  }
));
Run Code Online (Sandbox Code Playgroud)

使用req作为参数传递,验证回调可以使用请求的状态来定制身份验证过程,使用单个策略实例和路由集处理身份验证和授权.例如,如果用户已登录,则可以关联新"已连接"帐户.还可以使用在req上设置的任何其他特定于应用程序的属性,包括req.session.