← Study Notes Backend


Backend

JWT

A JSON token, signed with HMAC or RSA/ECDSA and Base64URL-encoded, carrying claims like user id and roles so the server can trust it statelessly without a session store. It is verified against a key or JWKS on each request. The catch: it cannot be revoked before it expires, so keep access tokens short-lived and pair them with refresh tokens.


Purpose

A JSON Web Token is a compact, signed token carrying claims — user id, roles, expiry — that a server can verify without a database lookup. It exists to make authentication stateless: the token itself is the proof, so any node can validate a request.

When to Use It

Good for stateless APIs, service-to-service calls, and single sign-on where one issuer signs tokens that many services verify. It pairs naturally with OAuth2/OIDC.

If you need instant revocation or store little per session, a plain opaque session in Redis is often simpler and safer.

Trade-offs

Statelessness is both the strength and the weakness: a JWT cannot be revoked before it expires, so a leaked token stays valid until then. Tokens bloat if overstuffed, and alg: none or weak-key mistakes are classic vulnerabilities.

Implementation

Sign with a strong algorithm (HS256 with a long secret, or RS256/ES256 with a key pair) and always verify the signature, exp, issuer and audience. Keep access tokens short-lived (minutes) and pair them with longer refresh tokens; validate against the issuer's JWKS. Never put secrets in the payload — it is only Base64, not encrypted.