Node.js Authentication: JWT and Passport.js

JWT authentication is the standard for Node.js APIs. Here’s how to implement it properly with Passport.js.

Setup

npm install passport passport-jwt jsonwebtoken bcryptjs

Generate Token

const jwt = require('jsonwebtoken');

function generateToken(user) {
  return jwt.sign(
    { id: user.id, email: user.email },
    process.env.JWT_SECRET,
    { expiresIn: '24h' }
  );
}

Passport Strategy

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;

passport.use(new JwtStrategy({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: process.env.JWT_SECRET
}, async (payload, done) => {
  const user = await User.findById(payload.id);
  return done(null, user || false);
}));

Protect Routes

app.get('/api/profile',
  passport.authenticate('jwt', { session: false }),
  (req, res) => res.json(req.user)
);

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.