freedomflyer
freedomflyer

Reputation: 2541

passport.authenticate not working as expected

Odd behavior, here. When I hit /login with correct username/password combo, it does in fact send me to the /secret route. When I use the wrong combination, it correctly redirects my right back to where I started.

However, if I try to "lock down" a route, say:

app.get('/mySecretRoute', passport.authenticate('local'), function(req, res, next){
    res.json({test:"secret"});
});

Then I get a 401: Unauthorized if I try to hit it after logging in. It appears that a cookie is indeed set, but maybe not the correct one. I have verified that the user is returned in the local strategy, and that serialization does grab the right user. How do I correctly configure passport to use the local strategy and lock down routes? I've looked through the documentation and it seems I am following the instructions.

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect(config.mongo.host + ':' + config.mongo.port + '/' + config.mongo.db_name);

app.get('/', routes.index);

app.get('/secret', function(req, res, next){
    res.render("secret");
});

app.get('/login', function(req, res, next){
    res.render("login");
});

app.post('/login', 
    passport.authenticate('local', { successRedirect: '/secret',
                                   failureRedirect: '/'
    })
);

app.get('/register', function(req, res, next){
    res.render('register');
});

app.post('/register', register);

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findByUsername(username, function(err, user) {
      console.log(username);
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

passport.serializeUser(function(user, done) {
     console.log(user._id);
  done(null, user._id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

function register(req, res, next) {
    console.log(req.body.username);
    console.log(req.body.password);

    User.addUser(req.body.username, req.body.password, function(err){
        if(err) throw new err;
    });
}


http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Upvotes: 1

Views: 448

Answers (1)

freedomflyer
freedomflyer

Reputation: 2541

For the most part, everything I originally posted works fine.

Despite the lack of good documentation on Passport's site, I was able to create a simple middleware to check if the user is logged in:

exports.loggedIn = function(req, res, next) {
    console.log('Checking credentials...');
    console.log(req.user);
    if(req.isAuthenticated()){
        next();
    } else {
        res.redirect("/");
    }
};

I'm not sure if this is the best way of doing it, but req.isAuthenticated is provided by Passport itself, so it must be somewhat standard.

Upvotes: 1

Related Questions