Cannot Post In An Express + Passport App / Authentication Test
I am trying to use Passport as an authentication middleware with Express - and Angular, if it matters. I have just started to know these frameworks and I experiment with a simple t
Solution 1:
You have to update some of express and passport requirements for this to work. Such as session, failureflash messages, serialize and deserialize. Here is updated code snippet for you. first you have to install "connect-flash" for this line of codes "failureFlash : true". But it will work without flash.
npm install connect-flash
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
flash = require('connect-flash');
Then update express environments:
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser());
// required for passport
app.use(express.session({ secret: 'my secret'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
// Authentication with Passport.jsvar testUser = {
username: 'patrik',
password: '123'
}
passport.use(new LocalStrategy(
function(username, password, done) {
if (username === testUser.username && password === testUser.password) {
return done(null, {username: username});
} else {
return done(null, {username: 'username or password incorrect!'});
}
return done(null, false);
}
));
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(username, done) {
done(null, {username: username});
});
app.get('/', routes.index);
app.post('/login',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true })
);
And here is a little update for your routes/index.js file:
exports.index = function(req, res){
var user = '';
if(req.session.passport.user !== undefined) user = req.user.username;
res.render('index', {title: user});
};
I hope these will help you to understand login with passport.
Post a Comment for "Cannot Post In An Express + Passport App / Authentication Test"