Express 3.0 and passport authentication

I am using express@3.0.0beta4 with a passport @ 0.1.12 and using local srategy for authentication.

Everything works fine and redirects to 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 makeAuthenticated to the 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 the login page) instead of '/ users / id' (user profile) after login. The problem is req.isAuthenticated () always returns false, and there is no req.user variable in debug.

Is this a problem with Express 3 and passport interaction, or did I do something wrong?

+4
source share
4 answers

I also had a similar problem, but it turned out that it was because I used express sessions without specifying a data store for the session data. This meant that the session data was stored in RAM, and since I used several workers, the session store was not shared between workers. I reconfigured my express session instead of RedisStore , and isAuthenticated() began to return true as expected.

 app.use express.session secret: '...' store: new RedisStore host: redisUrl.hostname port: redisUrl.port db: ... pass: ... 
+1
source

authenticate () is a middleware. from documents:

 app.post('/login', passport.authenticate('local', { failureRedirect: '/login' }), function(req, res) { res.redirect('/'); }); 
0
source

The problem was that I am testing it with curl -L -d "name=Test&password=1" and curl -L does not work as I expected. But it works fine with a web browser.

0
source

I also struggled with this problem for a long time. For me, this changed the maxAge property of the session cookie - it was too low:

 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() returns true

0
source

All Articles