javascript - Node.js Passport GoogleStrategy 如何访问 session 数据

标签 javascript node.js oauth-2.0 passport.js

我使用 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/

相关文章:

javascript - 来自同级容器的 FancyBox 标题

javascript - 单击按钮后组件未读取新的状态更改

java - Oauth2 身份验证后列出 Google 日历事件

javascript - socket.io 事件和自定义事件

c++ - NodeJS Addon 从 NAN AsyncWorker::Execute 内部调用 Javascript 回调

php - Google API 刷新 token

asp.net - 通过 WEB API 使用 ASP.NET Identity 进行本地登录

javascript - React-router-dom如何更新路由组件内的父状态

javascript - 如何在新页面中打开链接,然后从第二页链接回第一页

javascript - 在 document.ready 和 onClick 上运行函数