Lesson 36 / 38

Auth, JWT & Password Hashing

Understand HTTP Basic auth versus token-based auth, what a JWT actually contains and proves, and why passwords must be hashed with bcrypt, never stored in plain text.

Basic auth vs token auth

HTTP Basic sends a base64 (not encrypted!) username:password on every request — simple, but the password travels repeatedly and there's no session. Token-based auth (a JWT) is issued once at login and sent on later requests instead of the password, and can be scoped and expired independently.

What's inside a JWT

A JWT is three base64url parts joined by dots: header.payload.signature. The payload is a set of claims (sub, exp, roles) — readable by anyone, not secret. The signature is what a server can trust: it proves the payload wasn't tampered with, signed with a secret or private key only the issuer holds.

// decoded payload — anyone can read this, don't put secrets in it
{
  "sub": "user-42",
  "roles": ["ROLE_USER"],
  "exp": 1893456000
}

Never store plain-text passwords

Store a bcrypt hash of the password, never the password itself — bcrypt is deliberately slow and includes a per-password salt, which defeats rainbow tables and makes brute-forcing expensive. Verify by re-hashing the login attempt and comparing, never by decrypting (bcrypt hashes aren't reversible).

String hash = BCrypt.hashpw(rawPassword, BCrypt.gensalt());   // store `hash`

// on login:
boolean ok = BCrypt.checkpw(attempt, storedHash);