Node.js Advanced

Authentication & Security

JWT tokens, bcrypt, OAuth, session management, and security best practices.

Advertisement

Authentication & Security

JWT tokens, bcrypt, OAuth, session management, and security best practices.

Overview

Securing your Node.js application is critical. This lesson covers authentication strategies and security best practices.

Key Concepts

  • JWT (JSON Web Tokens) — Stateless authentication tokens
  • bcrypt — Password hashing with salt
  • OAuth 2.0 — Third-party authentication (Google, GitHub)
  • Session Management — Server-side sessions with cookies
  • Rate Limiting — Prevent abuse with request throttling
  • CORS — Cross-Origin Resource Sharing configuration

Code Examples

const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

// Register
async function register(name, email, password) {
  const hashed = await bcrypt.hash(password, 10);
  const user = await db.users.create({ name, email, password: hashed });
  const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '7d' });
  return { user, token };
}

// Middleware to verify token
function authMiddleware(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'No token provided' });
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
}

Practice

Build a complete auth system with registration, login, JWT tokens, and protected routes.