【问题标题】:Pass variable from Middleware to Passport in Express.js将变量从中间件传递到 Express.js 中的 Passport
【发布时间】:2016-03-25 13:06:50
【问题描述】:

我正在尝试将变量传递给中间件,并在使用 facebook-passport 成功进行身份验证后可用。

// route for facebook authentication and login
router.get('/connect/facebook', rentalinfo, passport.authenticate('facebook', { scope : 'email' }));

// handle the callback after facebook has authenticated the user
router.get('/connect/facebook/callback', passport.authenticate('facebook', {
    //successRedirect : '../../../protected',
    failureRedirect : '/'
}),
function(req, res) {
    // successful auth, user is set at req.user.  redirect as necessary.
    //Get the redirect location from the response
    //console.log(req.body);
    console.log(req.bookingarray);
    res.redirect('/protected'); 
});

我的中间件:

//Rent item middleware - carries rental info through signup/login process
function rentalinfo(req, res, next){
    //console.log('MIDDLEWARE VARIABLE: '+ bookingarray);
    req.bookingarray = 'SOMETHING';
    //return bookingarray;
    //if (something(res)) redirect('http://google.com'); // no access to your site
    next(); // go to routes
};

然后我尝试在我的 facebook 护照策略中访问它。

passport.use(new FacebookStrategy({
    // pull in our app id and secret from our auth.js file
    clientID        : configAuth.facebookAuth.clientID,
    clientSecret    : configAuth.facebookAuth.clientSecret,
    callbackURL     : configAuth.facebookAuth.callbackURL,
    profileFields   : ["emails", "displayName"],
    // this allows us to pass in the req from our route (lets us check if a user is logged in or not)
    passReqToCallback : true
},
// facebook will send back the token and profile
function(req, token, refreshToken, profile, done) {
    console.log(req.bookingarray);

    // asynchronous
    process.nextTick(function() {
        // check if the user is already logged in
        if (!req.user) {
            ...
        }
    }
}));

但是它只是返回未定义。我试过了,我错过了什么?目的是保持用户在认证前后的状态。

【问题讨论】:

  • 您的代码看起来不错。您确定那里没有任何错字或您分配给 bookingarray 的值已定义吗?没有其他代码会影响 req.bookingarray 吗?
  • 已经更新了 facebook 路由 /connect/facebook/ 和 /connect/facebook/callback。我知道在没有变量的情况下正确授权。非常感谢您的帮助,我一直在撞墙

标签: node.js express passport.js passport-facebook


【解决方案1】:

您需要将其存储在用户会话中,而不是具有一个请求生命周期的请求中。您的第二条路线是 Facebook 调用的 FB 回调,因此不会调用 rentalinfo 中间件,因此没有您的变量。

如果您不想使用会话(即无状态的 REST api 事物),那么您需要修改中间件以检查用户是否经过身份验证并从那里开始。这是否适合您将取决于您的情况。

【讨论】:

  • 感谢您的回复。我确实阅读了有关会话的信息,如果用户尚未通过身份验证,是否可以使用它们?
  • 进一步阅读后,我认为使用 state 参数可以让我将详细信息存储在表格中,并使用从 facebook 返回的 state ID 检索它们。有人见过这样的例子吗? stackoverflow.com/questions/6463152/…
  • 我最终使用 res.cookie 来临时存储一个 id,用于在数据库中查找一行以获取详细信息。
  • @Cookiejest - 会话不需要身份验证。它就像 cookie(它通常在幕后使用 cookie)。您可以使用 github.com/expressjs/session 并从 req.session 中添加/检索。使用 Cookie 就可以了,尽管需要手动创建它,因此需要做更多的工作。如果您希望您的数据比用户会话/访问的寿命更长,您可以使用 cookie。
猜你喜欢
  • 2017-08-17
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多