Topics Authentication & Security JWT Authentication
intermediate 18 min read

JWT Authentication

Implement JSON Web Token (JWT) based authentication with access and refresh tokens.

JWT Authentication

const jwt = require('jsonwebtoken');\nconst bcrypt = require('bcrypt');\n\nconst SECRET = process.env.JWT_SECRET || 'fallback-secret';\n\n// Hash password\nconst hashPassword = async (password) => {\n  return bcrypt.hash(password, 12);\n};\n\n// Compare password\nconst verifyPassword = async (password, hash) => {\n  return bcrypt.compare(password, hash);\n};\n\n// Generate tokens\nconst generateTokens = (userId, role) => {\n  const accessToken = jwt.sign(\n    { userId, role },\n    SECRET,\n    { expiresIn: '15m' }\n  );\n  \n  const refreshToken = jwt.sign(\n    { userId },\n    SECRET + '-refresh',\n    { expiresIn: '7d' }\n  );\n  \n  return { accessToken, refreshToken };\n};\n\n// Verify token middleware\nconst authenticate = (req, res, next) => {\n  const header = req.headers.authorization;\n  if (!header?.startsWith('Bearer ')) {\n    return res.status(401).json({ error: 'No token provided' });\n  }\n  \n  try {\n    const token = header.split(' ')[1];\n    const decoded = jwt.verify(token, SECRET);\n    req.user = decoded;\n    next();\n  } catch (err) {\n    return res.status(401).json({ error: 'Invalid or expired token' });\n  }\n};

Examples

const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const SECRET = 'my-secret-key';

// User registration
async function register(email, password) {
  // Check if user exists
  const existing = await db.users.findByEmail(email);
  if (existing) throw new Error('Email already registered');

  // Hash password
  const hashed = await bcrypt.hash(password, 12);

  // Save user
  const user = await db.users.create({ email, password: hashed });

  // Generate tokens
  const accessToken = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '1h' });
  const refreshToken = jwt.sign({ userId: user.id }, SECRET + '-refresh', { expiresIn: '7d' });

  return { user: { id: user.id, email: user.email }, accessToken, refreshToken };
}

// Login
async function login(email, password) {
  const user = await db.users.findByEmail(email);
  if (!user) throw new Error('Invalid credentials');

  const valid = await bcrypt.compare(password, user.password);
  if (!valid) throw new Error('Invalid credentials');

  const accessToken = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '1h' });
  return { user: { id: user.id, email: user.email }, accessToken };
}

console.log('Auth functions ready');

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.