I'm trying to get my Passport local strategy working.
I've got this middleware set up:
passport.use(new LocalStrategy(function(username, password, done) {
//return done(null, user);
if (username=='ben' && password=='benny'){
console.log("Password correct");
return done(null, true);
}
else
return done(null, false, {message: "Incorrect Login"});
}));
but then in here
app.use('/admin', adminIsLoggedIn, admin);
function adminIsLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
it always fails and redirects to the home page.
I can't figure out why this is happening? Why won't it authenticate?
In my console I can see that's Password Correct
is printing.
Why won't it work?
I also was facing same problem, but @PVThomas gives me solution, as in here in Answers. My problem was with
findById()
method indeserialize()
. I was usingfindOne()
infindById()
and then I replaced it withfind()
and nowreq.isAuthenticated()
is working fine. My app wasn't savingreq.session.passport.user
, It was returning undefined and then after replacement offindOne()
withfind()
it's saving user id inreq.session.passport.user
.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 optioncredentials:'include'
like so:The reason is because fetch doesn't support passing down cookies, which is necessary in this case.
My problem was that i set cookie.secure to true even if data was not over https.
Remember to set cookies to false if you're not using https
Also if you do believe you have https remember to trust the proxy
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,
I fixed this issue by fixing my passport.deserializeUser. I'm using mongo native and since most of the examples use Mongoose i fell in to the _id trap once again.
So remember to make the _id a mongo ObjectID when reading the user in deserializeUser
My query was not finding the user since I did not make the id an ObjectID, and there was no errors indicated anywhere.
Use Authentication in the below given manner it will work for sure as passport wants express-session for the isAuthenticated to work