Dave V
Dave V

Reputation: 1976

NodeJS, Passport & Passport-Local

So I'm running into an issue authenticating using a local strategy. If I pass invalid credentials or anything unsuccessful, I get the appropriate error. However, if they authentication is successful, then I'm presented with a 404 error.

I've dug around, and the best idea I ran across was dropping the session storage (which is where it seems to be happening, while serializing the user). Anyone encounter an issue like this?

Here's some of the code, if you need any other sections of code, let me know I'll gladly provide it.

My Passport configuration:

var passport = require('passport'),
User = require('mongoose').model('User');

module.exports = function () {
    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function (id, done) {
        User.findOne({ _id: id }, '-password -salt -__v', function (err, user) {
            done(err, user);
        });
    });

    require('./strategies/local')();
};

My Local Strategy configuration:

var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    User = require('mongoose').model('User');

module.exports = function () {
    passport.use(new LocalStrategy({
        usernameField: 'email'
    }, function (email, password, done) {
        User.findOne({email: email}, function (err, user) {
            if (err) {
                return done(err);
            }

            if(!user || !user.active || !user.authenticate(password)) {
                return done(null, false, { message: 'Authentication Failed'});
            }

            return done(null, user);
        });
    }));
};

All other methods work, I can query the DB to find the user, I have stepped through matching the hashed password with the provided password, it all seems to happen fine and I get a user at the end of the LocalStrategy (I make it to the final done(null, user). In the serializeUser() done(null, user.id) something happens. I've tried stepping through it, but what I end up getting into seems fairly obfuscated (or I'm too dumb to understand it) so I can't tell what's actually happening.

Upvotes: 0

Views: 638

Answers (1)

robertklep
robertklep

Reputation: 203359

This is your route setup:

app.route('/login').post(passport.authenticate('local'));

This will generate a 401 ("Unauthorized") when authentication fails, but when it succeeds, there isn't anything configured to happen next, so you'll get a 404.

You should add an explicit "success" handler to your route:

app.route('/login').post( 
  passport.authenticate('local'),
  function(req, res) {
    // This will only get called when authentication succeeded.
    res.json({ user : req.user });
  }
);

Upvotes: 1

Related Questions