部署到Heroku时,Passport req.isAuthenticated()始终为false

时间:2017-05-18 13:19:58

标签: node.js express heroku passport-local passport.js

我将passportNodejs一起使用。当我在localhost上运行时,我的应用程序按预期工作。但是,当我部署到Heroku时,我发现req.isAthenticated()函数在它应该返回true时返回false,即使护照正在查找并验证用户和密码。这是我的代码,用于初始化express-sessionpassport

app.use(cookieParser());
app.use(session({
  secret: 'foo',
  resave: true,
  saveUninitialized: true,
  cookie: {
    secure: true,
    maxAge: 3600000
    //maxAge: new Date(Date.now() + 3600000)
  }
}));

app.use(flash());
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

以下是我如何定义本地护照:

module.exports = function(passport, configIds) {
    passport.use('login', new LocalStrategy({
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true
    },
        function(req, email, password, cb) {
            //console.log('got email pwd: ' + email + ' ' + password);
        User.getByEmail(email, function(err, user) {
            if (err) { 
                console.log('something went wrong in login strategy getting user: ' + err);
                return cb(err); 
            }
            if (!user) { 
                console.log('problem with user in local strategy');
                return cb(null, false, { message: 'cannot locate user'}); 
            }
            if (!User.comparePassword(user, password)) { 
            console.log('incorrect password for user');
                return cb(null, false, { message: 'incorrect email or password'}); 
            }
          console.log('success: return the user');
            return cb(null, user);
        });
        }
    )),

我到达success: return the user控制台输出,并且当我在localhost上运行时,req.isAuthenticated()函数再次按预期返回true。我看到了一些关于使用https的评论,但我在localhost和Heroku上都使用了安全套接字。这是我定义的中间件,用于检查请求是否经过身份验证...

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated()) {
        next();
    } else {
        // if they aren't redirect them to the home page
        //return res.redirect('/');
        console.log('User not authenticated. Redirect to home');
        return res.status(401).redirect('/');
    }
}   

修改 我还检查了存储的cookie。我可以看到,当作为localhost运行时,会存储会话cookie,但是从Heroku运行时不存在cookie。

任何人都可以建议为什么这会工作,在localhost上运行但在Heroku上运行时会中断?

1 个答案:

答案 0 :(得分:0)

好的,现在这样做似乎是因为代理配置没有正确设置,正如程序员在其中一条评论中所建议的那样(谢谢!)。请参阅下面的修正代码,修复了问题...

app.use(cookieParser());
app.enable('trust proxy'); // add this line
app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true,
  proxy: true, // add this line
  cookie: {
    secure: true,
    maxAge: 3600000,
    store: new MongoStore({ url: config.DB_URL })
  }
}));

我还添加了一个MongoStore来保存robertklep建议的会话。希望这对任何面临同样问题的人都有帮助。