Passport.js& Express Session - req.user undefined导致.isAuthenticted()返回false

时间:2017-06-30 09:31:54

标签: node.js passport.js

我花了更多的时间来承认在网上搜索与我有同样问题的无数帖子,但无济于事。大多数解决方案似乎都不包括

  • passReqToCallback: true在我的LocalStrategy中。
  • 我的初始文件中有
  • passport.serializeUser()passport.deserializeUser()
  • app.js中的
  • app.use(passport.initialize())app.use(passport.session())
  • 在app.js中要求并使用app.use(cookieParser())
  • 将cookie解析器传递给我的密钥。
  • 将代理和cookie属性添加到app.js中的expressSession变量。
  • 在我的页面路由中的passport.authenticate内调用req.login。
  • 还有其他一些我不记得的小调整......

我的 login.js 如下;

var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user');
var bCrypt = require('bcrypt-nodejs');

module.exports = function(passport) {
    passport.use('login', new LocalStrategy({passReqToCallback: true},
        function(req, username, password, done) {
            //Queries MongoDB For User
            User.findOne({'username':  username}, function(err, user) {
                //In The Event Of An Error, Throw It
                if (err) {
                    return done(err);
                }

                //Username Does Not Exist, Log Error, Callback, Flash Error Message
                if (!user){
                    console.log('User: '+ username + ", does not exist.");
                    return done(null, false, req.flash('message', 'User Not found.'));
                }

                //User Exists, But Password Is Incorrect
                if (!isValidPassword(user, password)){
                    console.log('Invalid Password');
                    return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
                }

                //If No Previous Error Conditions Are Met - Username/Password Are Correct
                console.log("Validated User: " + username + ".");
                //req.user = user;
                return done(null, user);
            }); //End of User.findOne()
        }) //End of new LocalStrategy
    ); //End of passport.use()

    /*
    var isValidPassword = function(user, password){
        return bCrypt.compareSync(password, user.password);
    }
    */

    //Passwords are not currently hashed in my DB, so ignore bcrypt for now.
    var isValidPassword = function(user, password) {
        return user.password == password;
    }
}

我的 passport-init.js 文件

var login = require('./login');
var User = require('../../models/user');

module.exports = function(passport){
    //Serialise User
    passport.serializeUser(function(user, done) {
        console.log("Serializing User: " + user.username + "\n" + user + ".");
        done(null, user._id);
    });

    //De-Serialise User
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            console.log("Deserializing User: " + user.username + "\n" + user);
            done(err, user);
        });
    });

    //Setting up Passport Strategy for Login
    login(passport);
}

我的 index.js 文件包含POST登录路由

/* POST Login Page*/
router.post('/login', passport.authenticate('login', {
    successRedirect: '/dashboard',
    failureRedirect: '/login',
    failureFlash: true
}));

dashboard.js 包含/ dashboard / 其他页面的所有路由。 这些受isAuthenticated函数保护。

var express = require('express');
var router = express.Router();
var database = require('../public/javascripts/db-connect.js');

var isAuthenticated = function(req, res, next) {
    console.log("User: " + req.user);
    console.log("Authenticated?: " + req.isAuthenticated());
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect('/unauthorised');
    }
}

module.exports = function(passport) {
    //Routes /dashboard --> dashboard.pug
    router.get('/', isAuthenticated, function(req, res, next) {
        database.getData("busdata", function(err, data) {
            if (err) {
                console.error(err);
            } else {
                res.render('dashboard', {title: 'Dashboard', busdata: data});
            }
        });
    });

    //Routes /dashboard/journeys --> journeys.pug
    router.get('/journeys', isAuthenticated, function(req, res, next) {
        database.getData("journeydata", function(err, data) {
            if (err) {
                console.error(err);
            } else {
                res.render('journeys', {title: 'Journey Graphs', journeydata: data});
            }
        });
    });

    return router;
}

所以当我运行应用程序时;

  • 我检查localhost:3000/dashboardlocalhost:3000/dashboard/journeys。他们正确地将我改为/unauthorised
  • 导航至/login
  • 输入正确的用户名和密码,控制台随后吐出:
  • Validated User: TomPlum. 含义passport.use()已达return done(null, user)
  • Serialising User: TomPlum + the objects properties
  • POST /login 302 time ms
  • 来自User: undefined
  • isAuthenticated
  • isAuthenticated? false
  • GET /dashboard 302 time ms
  • Deserialising User: TomPlum + the objects properties
  • 然后我被重定向到/unauthorised,因为isAuthenticated()评估为false。

为什么req.user undefined?如果我的MongoDB -local,我应该使用LocalStrategy吗? (亚马逊Atlas服务器)。其他论坛帖子表明它可能是一个Cookie问题,但我已将相关的cookie-parser包含在我的app.js文件中。

app.js 就在这里,这是订单问题。

//Require Variables
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js

//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var dashboard = require('./routes/dashboard')(passport);

var app = express();
app.d3 = require('d3');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('urban_sensing'));
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', index);
app.use('/dashboard', dashboard);
app.use('/users', users);

//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.enable('trust-proxy');
app.use(expressSession({
    secret: 'urban_sensing',
    resave: true,
    saveUninitialized: true,
    proxy: true,
    cookie: {
        secure: true,
        maxAge: 3600000
    }
}));
app.use(passport.initialize());
app.use(passport.session());

//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());

//Initialize Passport

var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);

var index = require('./routes/index')(passport);
app.use('/', index);

//Catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

//Error Handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

某些app.use(expressSession({..}));属性目前可能是不必要的,因为它们是为了解决问题而添加的。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

经过太多时间后,结果就是app.js的顺序。

移动

var dashboard = require('./routes/dashboard')(passport);

app.use('/dashboard', dashboard);

低于所有护照配置。它现在正常工作。在护照代码之前的/仪表板路由期间,似乎没有正确初始化某些内容。

更新了app.js

//Require Variables
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js

//Page Routing
//var index = require('./routes');
var users = require('./routes/users');


var app = express();
app.d3 = require('d3');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('urban_sensing'));
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', index);

app.use('/users', users);

//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
    secret: 'urban_sensing',
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 3600000 //1 Hour
    }
}));
app.use(passport.initialize());
app.use(passport.session());

//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());

//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);

var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);

var index = require('./routes/index')(passport);
app.use('/', index);

//Catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

//Error Handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;