Node passport-local strategy always fails

I am using the Node.js Passport module to create an authentication process and I cannot figure out why the validation always fails even when I return success every time from the validation callback. To keep the example simple, I just use the passport-local strategy without persistent storage:

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var express = require('express');
var server = express();

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

passport.deserializeUser(function (id, done) {
  done(null, id);
});

passport.use(new LocalStrategy(
  function (username, password, done) {
    // Would perform lookup and verification here.
    // Instead return a valid user object every time.
    var user = { username: username };
    return done(null, user);
  }
));

server.post('/login', passport.authenticate('local', { failureRedirect: '/failure' }), function (req, res) {
  res.send('access granted');
});

var port = process.env.PORT || 3000;
server.listen(port,  function() {
  console.log('Listening on port ' + port);
});

      

Similar issues were solved by adding data serialization / deserialization methods using a placeholder, but I have them.

Here's the CURL call to push above with username and password:

curl -X "POST" "http://127.0.0.1:3000/login" \
  --data-urlencode "username=alice" \
  --data-urlencode "password=supersecret"

      

When I do this POST, the response contains an HTTP 302 redirect to redirect for /failure

every time, although I return null

(no error) and a dummy custom object in the callback LocalStrategy

. What am I missing?

+3


source to share


1 answer


I have reviewed two things:

  • There was no middleware call passport.initialize()

  • I didn't parse the request body because Express doesn't include this out of the box.


Now my block requires both of these elements at the top and it returns 200 OK when POSTING to /login

:

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var express = require('express');
var bodyParser = require('body-parser');
var server = express();
server.use(passport.initialize());
//server.use(passport.session()); -- For persistent login sessions
server.use(bodyParser.urlencoded({ extended: true }))

      

+6


source







All Articles