🔐

JSON Web Tokens (JWT)

Jul 18, 2024

JSON Web Tokens (JWT)

Introduction

  • JWTs help secure identity travel on the web but can be risky if stolen.
  • Speaker: Sahn, co-author of system design interview books.
  • Aim: Explore both the potential and dangers of JWTs.

Basics of JSON

  • JSON: Lightweight, human-readable and easy for machines to parse.
  • Serves as the payload in JWTs.

Structure of JWTs

  1. Header
    • Contains token type (usually JWT) and algorithm (e.g., HMAC SHA256, RSA).
  2. Payload
    • Contains claims (statements about an entity, typically the user).
    • Types of claims:
      • Registered (predefined like issuer, expiration time, subject).
      • Public
      • Private
    • Data in payload can be encoded but not necessarily encrypted.
  3. Signature
    • Ensures token hasn't been tampered with.

Signing Algorithms

  • Symmetric Algorithms (e.g., HMAC SHA256)
    • Uses shared secret key for signing and verification.
    • Fast and simple but key must be shared in advance.
  • Asymmetric Algorithms (e.g., RSA)
    • Uses a public/private key pair.
    • Private key for signing, public key for verification.
    • Allows verification without sharing private key but slower.

Use Cases and Standards

  • JWTs offer authentication, authorization, and secure information exchange.
  • Common in OAuth2 and OpenID Connect for authentication and authorization.

Avoiding Misuse

  • Sensitive data: Shouldn't be in the payload unless encrypted.
  • User Sessions: JWTs are stateless, making session management and token revocation challenging.

Common Vulnerabilities

  • Token Hijacking: Attackers steal a valid JWT to impersonate a user.
  • Weak Hashing Algorithms: Vulnerable to cryptographic weaknesses.
  • Brute Force Attacks: Attempt to crack token signatures.

Best Practices

  1. Keep JWT payloads compact.
  2. Use short token expiration times when possible.
  3. Store tokens securely.
  4. Invalidate leaked tokens quickly.
  5. Use strong signature algorithms.

Pros and Cons

Pros

  • Self-contained
  • Portable
  • No need for server-side storage

Cons

  • Vulnerable to theft (provides full resource access if intercepted).
  • Payload can become large, affecting performance.

Conclusion

  • JWTs offer scalable solutions for authentication, authorization, and information exchange if used properly.

Additional Resources

  • Subscribe to System Design newsletter at blog.bytebytego.com.