简体   繁体   English

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

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

I use Passport-Google-OAuth to implement registration/login on my demo site. 我使用Passport-Google-OAuth在演示站点上实现注册/登录。 It works very well. 效果很好。 Last several days I try to find solution how to access session variables inside "GoogleStrategy" implementation. 最近几天,我尝试找到一种解决方案,该解决方案如何在“ 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);
    });
}));

I don't know is this possible. 我不知道这可能吗。 I need to update existing user in database, not to create new one, but can't "get" _id of existing user in this function. 我需要更新数据库中的现有用户,而不是创建新用户,但是无法在此函数中“获取”现有用户的_id。

From the docs: http://passportjs.org/guide/authorize/ 从文档中: http : //passportjs.org/guide/authorize/

Association in Verify Callback 验证回调中的关联

Set the strategy's passReqToCallback option to true. 将策略的passReqToCallback选项设置为true。 With this option enabled, req will be passed as the first argument to the verify callback. 启用此选项后,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);
    }
  }
));

With req passed as an argument, the verify callback can use the state of the request to tailor the authentication process, handling both authentication and authorization using a single strategy instance and set of routes. 将req作为参数传递后,verify回调可以使用请求的状态来定制身份验证过程,使用单个策略实例和一组路由来处理身份验证和授权。 For example, if a user is already logged in, the newly "connected" account can be associated. 例如,如果用户已经登录,则可以关联新的“已连接”帐户。 Any additional application-specific properties set on req, including req.session, can be used as well. 也可以使用在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