Sometimes, we want to add user authentication for Node.js.
In this article, we’ll look at how to add user authentication for Node.js.
How to add user authentication for Node.js?
To add user authentication for Node.js, we can use Passport.
For instance, we write
passport.use(new LocalStrategy(
(username, password, done) => {
User.findOne({
username,
password
}, (err, user) => {
done(err, user);
});
}
));
app.post('/login',
passport.authenticate('local', {
failureRedirect: '/login'
}),
(req, res) => {
res.redirect('/');
});
to add Passport to the Express app
we have.
We call passport.use
with a LocalStrategy
instance to let us authenticate users by looking them up from our own MongoDB database.
We use User.findOne
to find the user.
Then we add the /login
route that uses the middleware returned by passport.authenticate
for authentication before we redirect to /
.
Conclusion
To add user authentication for Node.js, we can use Passport.