How do JWTs, OAuth, and Passport.js fit together in a typical Node.js authentication architecture?
Short answer
They operate at different layers: OAuth 2.0 is the protocol governing how a user grants a third-party application access without sharing their password directly; JWT is a token format commonly used to represent the resulting authenticated session or access grant in a compact…
Advertisement
AModel answer
They operate at different layers: OAuth 2.0 is the protocol governing how a user grants a third-party application access without sharing their password directly; JWT is a token format commonly used to represent the resulting authenticated session or access grant in a compact, verifiable way; and Passport.js is a middleware library providing a consistent interface for implementing many different authentication strategies (including OAuth providers and JWT verification) within an Express application, so they're often used together rather than being competing choices.
const passport = require('passport');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
}, async (payload, done) => {
const user = await User.findById(payload.sub);
return user ? done(null, user) : done(null, false);
}));Real-world example
An application uses Passport's GoogleStrategy for the initial OAuth login handshake with Google, then issues its own JWT for subsequent API requests, verified on each request by Passport's JwtStrategy -- combining all three pieces into one coherent authentication flow.
Likely follow-ups
- Why does the application issue its own JWT rather than just continuing to use Google's access token directly for every API call?
- How does Passport's serializeUser/deserializeUser differ when using JWTs (stateless) versus sessions (stateful)?
Related topics