I'm using the Node.js Passport module to build an authentication process, and I'm unable to figure out why the verification always fails, even when I return success every time from the verification callback. To keep the example simple, I'm just using the passport-local strategy with no 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 questions have been solved by adding placeholder user serialization/deserialization methods, but I've got those in place.
Here's a CURL call to hit the above with a username and password:
curl -X "POST" "http://127.0.0.1:3000/login" \
--data-urlencode "username=alice" \
--data-urlencode "password=supersecret"
When I perform that POST, the response contains the HTTP 302 failure redirect to /failure
every time, even though I'm returning null
(no error), and a dummy user object in the LocalStrategy
callback. What am I overlooking?
I was overlooking two things:
passport.initialize()
middlewareNow my require block at the top includes both of those missing items, 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 }))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With