node.js - 在 Express.js 中将变量从中间件传递到 Passport

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

我正在尝试将变量传递给中间件,并在使用 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 策略中访问它。

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) {
            ...
        }
    }
}));

但是它只是返回为未定义。我已经尝试过了,我还缺少什么吗?目的是保存用户认证前后的状态。

最佳答案

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

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

关于node.js - 在 Express.js 中将变量从中间件传递到 Passport,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362118/

相关文章:

javascript - 不要在循环中创建函数 no-loop-func -React JS

mysql - 调用退出后无法排队查询

node.js - 从 Node API 加载 Web Audio API 中的音频

javascript - node.js 应用程序在 AWS 上停止的问题

node.js - 制造商 ldapjs 使用 tls

node.js - 使用 Node Express 处理大型 ZIP 包的 Zip 创建流程

node.js - nodejs + passport + express 3.0 + connect-flash 不闪烁?

express - 使用 Passport.js 和 Express-Session 作为中间件在 NodeJS 应用程序中获取 "TypeError: Secret string must be provided."

node.js - FacebookGraphAPI错误: (#210) This call requires a Page access token

IOS Facebook 认证使用 node.js passport-facebook-token