I'm using express@3.0.0beta4 with passport@0.1.12 and using local srategy for authentication.
Everything seems to work fine and it redirects on success and failure correctly
app.post('/login', passport.authenticate('local', { failureRedirect: '/' }),
function(req, res) {
console.log(req.isAuthenticated()); // true
res.redirect('/users/' + req.user.id );
});
But if I add ensureAuthenticated on profile route
app.get('/users/:id', ensureAuthenticated, routes.user);
function ensureAuthenticated(req, res, next) {
console.log(req.isAuthenticated()); // false
if (req.isAuthenticated()) { return next(); }
res.redirect('/');
}
it redirects me back to '/' (which is login page) instead of '/users/id' (user profile) after login. The problem is req.isAuthenticated() always return false and there is no req.user variable in debug.
Is it problem with express 3 and passport interaction or I did something wrong?
I had a similar problem too, but turns out it was because I was using express sessions without specifying a data store for session data. That meant session data was being stored in RAM, and since I was using multiple workers, the session storage wasn't shared between workers. I reconfigured my express session to use a RedisStore
instead, and isAuthenticated()
started returning true as expected.
app.use express.session
secret: '...'
store: new RedisStore
host: redisUrl.hostname
port: redisUrl.port
db: ...
pass: ...
authenticate() is middleware. from the docs:
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
The problem was that I test it with curl -L -d "name=Test&password=1"
and curl -L
do not work as I expected. But it works just fine with web-browser.
I was also struggling with this issue for ages. What fixed it for me was changing the maxAge
property of the session cookie - it was too low before:
app.use(express.cookieParser());
app.use(express.session({
secret: config.session.secret,
cookie: {
maxAge: 1800000, //previously set to just 1800 - which was too low
httpOnly: true
}
}));
After this change, req.isAuthenticated()
returned true