passport's req.isAuthenticated always returning false, even when I hardcode done(null, true)
I had a similar issue. Could be due to the express-session middleware needed for passport. Fixed it by using middlewares in the following order: (Express 4)
var session = require('express-session');// required for passport sessionapp.use(session({ secret: 'secrettexthere', saveUninitialized: true, resave: true, // using store session on MongoDB using express-session + connect store: new MongoStore({ url: config.urlMongo, collection: 'sessions' })}));// Init passport authentication app.use(passport.initialize());// persistent login sessions app.use(passport.session());
FOR NEWBIES
I was facing a similar problem, where my isAuthenticated() function would return false.I lost a lot of time, hope this answer saves yours.
Some Common problems to watch out for,
- Middleware setup order (express-session > pass.initialize > pass.session ).
- Serialize and Deserialize methods needs to pass user on the request.(For more info I've posted an answer on this link.. Basics of Passport Session (expressjs)-why do we need to serialize and deserialize? ) if there's no user on request then isAuthenticated would return false.... and redirect to the PATH defined ......when false....
- The getUserById or findById function defined in the model(user.js) needs to have a User.findById (and not User.findOne) function defined.(this function would load user on the request in every session)
This could also be an issue with your client's POST/GET calls. I had this exact same issue but it turned out that I had to give fetch
(which is what I was using) the option credentials:'include'
like so:
fetch('/...', { method: 'POST', headers: myHeaders, credentials: 'include', body: ... ...})
The reason is because fetch doesn't support passing down cookies, which is necessary in this case.