Passport.js
Passport & Strategies
1. The Theory: What is a Strategy?
Theory: In Passport, a Strategy is a modular piece of code that handles a specific way of authenticating a user
Plug-and-Play: You can have multiple strategies in one app (e.g., one for email/password and another for Google login)
. Abstraction: Your routes don't need to know how the user is authenticated; they just need to know if Passport says "Success" or "Failure"
.
2. Common Types of Strategies
Local Strategy (passport-local)
Theory: This is used for traditional username and password authentication where the credentials live in your own database
Process: Passport extracts the username and password from the
req.body, and you provide a "verify callback" to check them against your DB.
JWT Strategy (passport-jwt)
Theory: Used for securing APIs with JSON Web Tokens
Process: It looks for a token in the
Authorizationheader, verifies the signature using your secret key, and then finds the user associated with that token.
OAuth Strategies (Google, Facebook, GitHub)
Theory: These allow users to log in using their accounts from other platforms
Process: These follow a redirect flow: your app sends the user to Google → Google verifies the user → Google sends a "code" back to your app → Passport swaps that code for a user profile
.
3. The Middleware Flow
Theory: Passport operates in a specific sequence within the Request Lifecycle
Initialize:
app.use(passport.initialize())sets up Passport to handle incoming requests. Session Support: If using sessions,
app.use(passport.session())allows Passport to serialize/deserialize user info into the session. Authentication Guard: You place
passport.authenticate('strategy-name')on the routes you want to protect.
4. Implementation Example (Local + JWT)
Defining a Strategy
passport.use(
'test',
new LocalStrategy(
{ usernameField: 'email' },
async (email, password, done) => {
try {
const user = await User.findOne({ email });
if (!user || !user.verifyPassword(password)) {
return done(null, false, {
message: 'Invalid credentials'
});
}
return done(null, user);
} catch (err) {
return done(err);
}
}
)
);Protecting a Route
app.post(
'/login',
passport.authenticate('test'),
(req, res) => {
res.json({
message: 'Login successful',
user: req.user
});
}
);