What is passport-local?
The passport-local npm package is a Passport strategy for authenticating with a username and password. It is designed to be simple and unopinionated, allowing developers to implement their own authentication logic.
What are passport-local's main functionalities?
Local Strategy Setup
This code sets up the LocalStrategy for Passport, which will authenticate users based on a username and password. The `User.findOne` function is a placeholder for your user lookup logic.
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Incorrect username.' }); }
if (!user.validPassword(password)) { return done(null, false, { message: 'Incorrect password.' }); }
return done(null, user);
});
}
));
Serialize and Deserialize User
These functions are used to serialize the user information into the session and deserialize it back. This is necessary for maintaining login sessions.
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
Middleware for Authentication
This code demonstrates how to use the `passport.authenticate` middleware in an Express route to handle user login. It redirects users based on the success or failure of the authentication.
app.post('/login',
passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login', failureFlash: true })
);
Other packages similar to passport-local
passport-jwt
The passport-jwt package is a Passport strategy for authenticating with a JSON Web Token. It is used for stateless authentication, where the token is usually sent in the HTTP headers. Unlike passport-local, which uses sessions, passport-jwt is suitable for APIs and mobile applications.
passport-oauth2
The passport-oauth2 package is a Passport strategy for authenticating with OAuth 2.0. It is used for third-party authentication providers like Google, Facebook, and GitHub. This package is more complex than passport-local as it involves redirecting users to the provider's site for authentication.
passport-google-oauth20
The passport-google-oauth20 package is a Passport strategy for authenticating with Google using OAuth 2.0. It is specifically tailored for Google authentication and provides a streamlined way to integrate Google login into your application, unlike passport-local which is for username and password authentication.