user2817219
user2817219

Reputation: 331

passport local mongoose req.user undefined

I'm currently encountering the following problem during implementation of passport js with the passport local mongoose plugin. Account creation and logging in is working correctly. However, after I have logged in passport never identifies me as a user that is logged in.

I have used the following pieces of code:

In my user model:

User.plugin(passportLocalMongoose);

In app.js (this order of inclusion is correct?):

app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('keyboard cat'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'keyboard cat' }));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

In my routes:

router.post('/login', passport.authenticate('local'), function(req, res) {
  res.json({ loggedIn: true });
});

which returns true, but the following keeps returning false (after logging in):

req.isAuthenticated()

Can anyone enlighten me what the cause may be?

Thanks!

Upvotes: 0

Views: 1045

Answers (2)

prateekm33
prateekm33

Reputation: 111

From the looks of it, your order is fine. The most important part of the order is to have passport.initialize() and passport.session() come after your express-session configuration.

As for the issue with the initial authentication working, but subsequent requests showing an unauthenticated user, the issue could very well be because of cookies. I have run into a similar issue before, and the problem was in the way the HTTP requests were being made from the client.

If you are using the ES6 fetch API, then you will want to make sure to pass in an key credentials to the options object with a value of "include".

For example:

fetch('/restricted', {
  method: 'get',
  credentials: 'include'
});

The fetch API will not send credentials in cookies unless you specify it to. Hope this helps.

Additional resources: https://developers.google.com/web/updates/2015/03/introduction-to-fetch

Upvotes: 1

Huston Hedinger
Huston Hedinger

Reputation: 511

You probably want to try an Express middelware, as was suggested in the comments.

For example:

 function isAuthenticated(req, res, next) {
    if(req.isAuthenticated()) {
        return next()
    } else {
        // redirect users to login page
    }
 }

 app.get('/anypage', isAuthenticated, function(req, res) {
    // some reoute logic
 })

Upvotes: 1

Related Questions