3
votes

I use the module passport to create authentication with session .. But since express v4 , there is no more tutorial .. and my authentication doesn't work , in effect in my function that verify if the user is authenticated , the req.user is always undefined and req.isAuthenticated is false !

exports.ensureAuthenticated = function(req, res, next) {    
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login');
}

app.use(connect.logger('dev')); 
app.use(express.static('public'));
app.use(connect.cookieParser());
app.use(bodyParser());
app.use(connect.cookieSession({ secret: 'keyboard cat', cookie: { secure: true }})); 
app.use(passport.initialize());
app.use(passport.session());

Any solution ?

2

2 Answers

7
votes

Passport works with Express 4 just fine.

I had the same problem when trying to user Angularjs, turns out the user wasn't logging in the first place. Are your passport.serializeUser and passport.deserializeUser functions being called? If that's the case, are you using custom callbacks? When following a tutorial that did not user Angularjs I had to use a custom callback:

    router.post('/login', function (req, res, next) {
        passport.authenticate('local-login',  function (err, user, info) {
            if (err) {
                return next(err); // will generate a 500 error
            }
            if (!user) {
                return res.send({ success : false, message : info.message || 'Falha no login' });
            }

            req.logIn(user, function(err) {
                if (err) { return next(err); }
                return res.send({ success : true, message : 'Login efetivado com sucesso', user: user });
            });

            //return res.send({ success : true, message : 'Login efetivado com sucesso', user: user });
        })(req, res, next);
    });

I was not calling req.logIn, so the user was never serialized/deserialized and req.isAuthenticated() was always false.

5
votes

If you have cookie.secure set to true and you're NOT using SSL (i.e. https protocol) then the cookie with the session id is not returned to the browser and everything fails silently. Removing this flag resolved the problem for me.

app.use(session({ 
    secret: 'something', 
    cookie: { 
        secure: true
}}));