contentintech
Learn/System Design/Identity, JWTs & System Security
Intermediate~15 min read

Identity, JWTs & System Security

Design sessions, token lifecycles, authorization boundaries, tenant isolation and secure service communication.

System DesignDistributed SystemsInterviews

Authentication is only the first decision

Authentication establishes who or what is calling. Authorization determines what that identity may do. A valid token does not make GET /users/another-user/resume acceptable. Derive the owner from verified identity and check resource permissions server-side.

Use a threat model: assets, callers, trust boundaries, abuse paths and recovery. For a hiring portal, resumes, contact details and account credentials deserve different protections from public company descriptions.

Session IDs vs access tokens

ChoiceValidationRevocation trade-off
Opaque session IDLookup in an authoritative session store or cacheCentral control; store availability matters
Signed access JWTVerify signature and claims using trusted keysLocal verification; stale permissions can last until expiry
Opaque API tokenLookup or introspectionSimple central policy; protect and rotate the secret

JWT is a format, not a complete login protocol. A signed JWT payload is readable, so avoid secrets and unnecessary personal data inside it. Encryption is separate from signing.

Access and refresh lifecycle

text
Login -> access token + refresh credential
Request -> verify access -> authorize resource -> execute
Access expires -> refresh endpoint -> rotate credentials -> retry once
Logout -> revoke refresh session -> clear browser credentials

Short access lifetimes limit exposure. A refresh credential grants the ability to obtain future tokens and should be treated as a high-value secret. Rotation and reuse detection can identify stolen refresh credentials, but concurrent refresh requests need coordination to avoid treating legitimate races as theft.

Local access-token verification does not automatically reflect a revoked session or changed admin role. For sensitive operations, add a current permission/session check or choose a bounded revocation cache. State the latency and revocation requirement rather than calling all DB checks wasteful.

Read a signed JWT without trusting it

A compact signed JWT has three dot-separated parts: encoded header, encoded claims and signature. Encoding is not encryption: a recipient can inspect ordinary claims without a secret.

Part or claimMeaningWhat the verifier must decide
HeaderAlgorithm and optional key identifierIs this algorithm permitted, and is the key trusted?
iss / audIssuer / intended recipientWas this token issued for this API?
subSubject identifierWhich identity does it represent?
exp / nbfExpiry / earliest accepted timeIs the token valid now?
iat / jtiIssue time / token identifierDoes an application policy need these?

With HMAC, a shared verification secret can also sign tokens. With asymmetric signing, the issuer keeps the private key and APIs verify with public keys. Neither approach makes claims trustworthy before validation. A token ID alone does not prevent replay; that requires state or another protocol-level defense.

JWT validation checklist

Use a maintained verifier; do not implement cryptography yourself. Configure accepted algorithms independently of untrusted token headers. Validate the signature, issuer, intended audience, expiry and relevant time claims, with bounded clock tolerance. Separate token purposes so an ID token cannot silently become an API access token. Only fetch signing keys from a trusted configured issuer; cache keys and handle rotation without unbounded network fetches.

OAuth and OpenID Connect

OAuth delegates access; OpenID Connect adds an identity layer. For browser/mobile authorization-code flows, PKCE binds the code exchange to the initiating client. Exact redirect URI validation, state and appropriate nonce handling prevent different classes of attacks. Client secrets cannot remain secret inside downloadable frontend JavaScript.

Scopes describe delegated capabilities, but resource ownership and organizational roles still need enforcement. An orders:read scope does not necessarily permit reading every tenant's orders.

Browser credentials, XSS and CSRF

HttpOnly cookies reduce JavaScript access to credentials; Secure restricts transmission to HTTPS. SameSite helps with cross-site request behavior, but choose it for the actual flow and add CSRF defenses where required. Cookies automatically accompany matching requests, while an Authorization header is explicitly attached by the application. Neither storage choice fixes XSS: prevent injection and apply a defensible CSP.

CORS controls browser cross-origin response access. It is not authentication, and non-browser clients are not constrained by it. Never expose service-role keys because a request came from an approved origin.

Multi-tenant and service security

Choose shared tables with mandatory tenant predicates, separate schemas or separate databases according to isolation and operational needs. Enforce isolation at more than one layer where possible: application checks plus database policies. Keep cache keys, queue envelopes, search filters and object-storage paths tenant-aware.

Service identity can use short-lived workload credentials and mTLS. TLS protects a channel; authorization still controls which service can call which operation. Rotate secrets through a secret manager, redact logs and give each service the minimum privileges it needs. Encrypt backups, define retention and verify deletion reaches derived stores.

Worked authorization exercise

An authenticated user requests application A17. Load it using both ID and verified user ID, returning a safe missing/forbidden outcome according to your enumeration policy. A separate administrative action checks the current admin entitlement, writes an audit event and avoids logging the entire resume. A cache entry must preserve the same ownership boundary.

Test stolen/expired tokens, wrong audiences, changed roles, cross-tenant IDs, leaked signed URLs and replay. A login happy path is insufficient evidence of security.

Next: API design and reliability.

Section navigation