ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Node.js Tutorial• 9 min read

User Authentication with JWT & Bcrypt

Hashing passwords securely and issuing signed stateless tokens

Modern microservices utilize JSON Web Tokens (JWT) for stateless, scalable user authentication. Combining bcrypt for one-way password hashing with signed JWTs creates an enterprise-ready security foundation.

The JWT Authentication Lifecycle

Registration: The user submits a plain-text password. The server hashes it with bcrypt.hash(password, 12) using a random cryptographic salt.

Login: The server retrieves the hashed password and verifies the attempt with bcrypt.compare(). If valid, it signs a JWT using a private secret.

Token Anatomy: A JWT consists of three Base64URL parts separated by dots: Header, Payload, and Signature.

Authorization Guard: Incoming protected requests present the token in the Authorization: Bearer <token> header, verified with jwt.verify().

JWT Authentication Middleware in Node
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';

const JWT_SECRET = process.env.JWT_SECRET || 'super-secret-key-123';

// 1. Password Hashing
export async function securePassword(plainText) {
  const saltRounds = 12;
  return await bcrypt.hash(plainText, saltRounds);
}

// 2. Token Issuance
export function generateToken(user) {
  return jwt.sign(
    { sub: user.id, email: user.email, role: user.role },
    JWT_SECRET,
    { expiresIn: '2h' }
  );
}

// 3. Auth Guard Middleware
export function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // "Bearer TOKEN"

  if (!token) {
    return res.status(401).json({ error: 'Access denied: No token provided' });
  }

  jwt.verify(token, JWT_SECRET, (err, decodedUser) => {
    if (err) {
      return res.status(403).json({ error: 'Invalid or expired token' });
    }
    req.user = decodedUser;
    next();
  });
}
jwt.verify decodes the payload while asserting signature authenticity and expiration.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which header standard carries the JWT token in client HTTP requests?