JWT Authentication: Securing Your REST API

JSON Web Tokens (JWT) are a compact way to represent claims between parties. For stateless REST APIs and SPAs, JWT-based auth is a standard pattern-when implemented correctly.

Token Structure

A JWT has three Base64-encoded parts: header, payload, and signature. The server signs the token with a secret (HS256) or private key (RS256). Clients send Authorization: Bearer <token> on each request.

Issuing Tokens in Node.js

const jwt = require('jsonwebtoken');

function login(req, res) {
  const user = validateCredentials(req.body);
  if (!user) return res.status(401).json({ error: 'Invalid credentials' });

  const token = jwt.sign(
    { sub: user.id, role: user.role },
    process.env.JWT_SECRET,
    { expiresIn: '1h' }
  );
  res.json({ token });
}

Middleware Verification

function authMiddleware(req, res, next) {
  const header = req.headers.authorization;
  if (!header?.startsWith('Bearer ')) return res.sendStatus(401);
  try {
    req.user = jwt.verify(header.slice(7), process.env.JWT_SECRET);
    next();
  } catch {
    res.sendStatus(401);
  }
}

Security Checklist

Keep secrets out of source control. Use short expiration and refresh tokens for long sessions. Never store sensitive data in the payload-it is readable. Prefer HTTPS everywhere.

Conclusion

JWT auth scales well for distributed APIs. Pair it with refresh tokens, rate limiting, and server-side revocation lists when you need stronger session control.