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

Solution 1:

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());

Solution 2:

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,

  1. Middleware setup order (express-session > pass.initialize > pass.session ).
  2. 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....
  3. 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)

Solution 3:

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.

Solution 4:

My problem was that i set cookie.secure to true even if data was not over https.

app.use(require('express-session')({
    secret: process.env.sessionSecret,
    cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
    },
    store: store,
    resave: false,
    saveUninitialized: false,
    cookie: { secure: false } // Remember to set this
}));

Remember to set cookies to false if you're not using https

cookie: { secure: false } // Set to false

Also if you do believe you have https remember to trust the proxy

app.set('trust proxy', 1) // trust first proxy