Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passport's req.isAuthenticated always returning false, even when I hardcode done(null, true)

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?

like image 622
CodyBugstein Avatar asked Mar 17 '15 23:03

CodyBugstein


People also ask

What does req isAuthenticated () do?

The “req. isAuthenticated()” function can be used to protect routes that can be accessed only after a user is logged in eg. dashboard.

What does Passport local mongoose do?

Passport-Local Mongoose is a Mongoose plugin that simplifies building username and password login with Passport.

What is passport session?

passport. session() acts as a middleware to alter the req object and change the 'user' value that is currently the session id (from the client cookie) into the true deserialized user object.

What is NPM passport local?

This module lets you authenticate using a username and password in your Node. js applications. By plugging into Passport, local authentication can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.


1 Answers

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 session app.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()); 
like image 86
Nitin Avatar answered Oct 12 '22 01:10

Nitin