Node.js › Authentication & Authorization
What is Passport.js, and how do its 'strategies' provide a consistent authentication abstraction across different methods?
IntermediateAnswer
Passport.js is a widely used Express-compatible authentication middleware built around the concept of 'strategies' -- pluggable modules each implementing one specific authentication method (local username/password, Google OAuth, JWT, SAML, and hundreds of others) behind a consistent interface, so an application can support multiple authentication methods side by side, or switch between them, with minimal changes to route-handling code.
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(async (username, password, done) => {
const user = await User.findOne({ username });
if (!user || !(await user.comparePassword(password))) return done(null, false);
return done(null, user);
}));
app.post('/login', passport.authenticate('local'), (req, res) => res.json({ success: true }));Real-world example An application supporting both traditional username/password login and 'Sign in with GitHub' registers both a LocalStrategy and a GitHubStrategy with Passport, letting both authentication paths converge on the same req.user object and the same downstream authorization logic.