I'm trying to find resources about the most simple login with passport for a node app. I mean, using:
middleware:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('public'));
passport:
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
done({ id: id, nickname: "test"})
});
passport.use(new LocalStrategy(
function(username, password, done) {
console.log("test");
if (username === 'username') {
return done(null, { name: "test", id: '1234'});
} else {
return done(null, false, { message: 'Incorrect cred.' });
}
})
)
and redirection:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/index.html',
failureRedirect: '/login'
})
);
my app structure:
/app.js
/public/index.html
/public/login.html
And that's it. the Web is full of the same examples of Mongoose with plugins, everyone simply copy-pasting from each other.
The point is that I would like, later on, to insert my own code ti the LocalStrategy code (would probably used LDAP).
Currently, instead of redirecting to /index.html with the page created in the public folder, I just receive [object Object]
on index.html.
Your passport.deserializeUser()
is incorrect:
passport.deserializeUser(function(id, done) {
done({ id: id, nickname: "test"})
});
It's passing the "user" object as first argument to done
, which is reserved for errors. This causes Express to render an error page where it tries to stringify the error, resulting in [object Object]
.
Try this:
passport.deserializeUser(function(id, done) {
done(null, { id: id, nickname: "test"})
});
Found the issue! the redirection didn't work, so I looked back up and noticed that the express.static mw was set AFTER the passport initialize(), and not BEFORE. I just moved it up to the top and.. rainbows
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