如何将令牌从中间件传递到路由

时间:2014-08-11 00:31:28

标签: node.js passport.js

这是我的Passport中间件。我可以看到你正在登录Instagram:

// Use the InstagramStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Instagram
//   profile), and invoke a callback with a user object.
passport.use(new InstagramStrategy({

    clientID: INSTAGRAM_CLIENT_ID,
    clientSecret: INSTAGRAM_CLIENT_SECRET,
    callbackURL: INSTAGRAM_CALLBACK_URL
  },

  function(accessToken, refreshToken, profile, done) {

    // asynchronous verification, for effect...
    process.nextTick(function () {

      var oauth = {'accessToken' : accessToken,
                 'refreshToken' : refreshToken,
                      'profile' : profile
                  };


      return done(null, oauth);
    });
  }
));

然后是我的回调路线:

  app.get('/auth/instagram/callback', 
    passport.authenticate('instagram', { failureRedirect: '/home/language' }),
    function(req, res) {

      var oauth = req.get({oauth : oauth}); // Tried this first
      var oauth = req.oauth; // And this second
  });

我在此回调中从oauth获取变量req时遇到问题,因此我可以获取访问令牌并在此处设置req.sessions

*当然,我没有同时拥有这两个var oauth = ...语句。为了简洁起见,将它们展示在一起。

1 个答案:

答案 0 :(得分:1)

所以我在Google Group thread然后the docs中看到了这个功能:

passReqToCallback: true

因为现在我想要做的就是将令牌保存到会话中,我可以这样做:

  passport.use(new InstagramStrategy({

    clientID: INSTAGRAM_CLIENT_ID,
    clientSecret: INSTAGRAM_CLIENT_SECRET,
    callbackURL: INSTAGRAM_CALLBACK_URL,
    passReqToCallback: true // ADD THIS!
  },

  function(req, accessToken, refreshToken, profile, done) { // `req` is first parameter

      req.session.IGAccessToken = accessToken; // Set tokens on session
      req.session.IGRefreshToken = refreshToken;

      return done(null, profile);
  }
));

现在我可以在任何路线上访问令牌。