Reputation: 43843
I am new to node.js authentication. I want to use passport, passport-local, to do some basic authentication. But when I try it, it always goes to authentication failed.
I am following this tutorial http://www.sitepoint.com/local-authentication-using-passport-node-js/
This is what I have so far:
var express = require('express');
var app = express();
var qs = require('querystring');
var pg = require('pg');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
//var expressSession = require('express-session');
//app.use(expressSession({secret: 'mySecretKey', cookie: { maxAge: 60000 }, resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
// in here I know I am supposed to connect to database, and check if the username,password is there, but for now, i'll just force it to return a user, like they exist.
passport.use(new LocalStrategy(function(username, password, done) {
console.log(1); // does not even print this
//return done(null, false);
var r = done(null, {
'username': username,
'password': password
});
console.log(r);
return r;
}));
/*
* Visit the home page.
*/
app.get('/', function (req, res) {
var dest = 'index.html';
res.sendFile(dest, { root: __dirname });
});
/*
* Login.
*/
app.post('/login',
passport.authenticate('local', {
successRedirect: '/loginSuccess.html',
failureRedirect: '/loginFailure.html'
})
);
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('My App started at http://%s:%s', host, port);
});
Does anyone know what's wrong with this?
Also can anyone explain how this basic authentication works, and what the serialize/deserialize functions are for?
Thanks
Upvotes: 2
Views: 796
Reputation: 203304
Your app is lacking the body-parser
middleware, which is required to parse incoming POST
data.
...
app.use(bodyParser.urlencoded({ extended : true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
...
Upvotes: 2