01. Authentication, Identity, and Tokens¶
⏱️ Estimated time: 30 min | Level: intermediate
ELI5 callback: In the apartment building, the front door checks identity, the elevator key limits movement, the wall keeps tenants apart, the audit records rule-following, and the safe protects valuables.
1) What problem authentication really solves¶
Authentication answers one question only: who is making this request right now?
Everything downstream depends on that answer being trustworthy. See. If identity is weak, every later control becomes decoration.
So what to do? Separate login, session, and authorization decisions in your architecture notes.
Human users, service accounts, and background workloads need different identity proof. One path for all actors usually becomes messy.
Now watch. A good design names the identity provider, the token issuer, the client type, and the trust boundary.
- The front door reminds you that identity is checked first.
- The elevator key reminds you that permissions come after identity.
- The wall reminds you that tenant separation is a different control.
- The audit reminds you that proof and evidence matter in production.
-
The safe reminds you that secrets and data still need encryption.
-
Use a stable internal subject identifier instead of trusting email addresses forever.
- Decide early whether the app trusts an external IdP, an internal issuer, or both.
- List which requests come from browsers, mobile apps, CLIs, and service meshes.
- Write down what happens when identity proof fails, expires, or is revoked.
2) OAuth 2.0 and OIDC without confusion¶
OAuth 2.0 is mainly about delegated access. OIDC adds a clean identity layer on top.
People say login with OAuth all the time. Strictly speaking, identity claims arrive through OIDC.
Use the authorization code flow with PKCE for browser and mobile clients. Simple, no?
Avoid the implicit flow in modern systems. Tokens in the browser fragment are too exposed.
An identity token tells the client who logged in. An access token tells APIs what was issued.
- Validate issuer, audience, expiry, and signature before trusting any token.
- Pin redirect URIs carefully because sloppy callback rules invite token theft.
- Use scopes for coarse API delegation, not as a dumping ground for every product rule.
- Keep subject identifiers immutable even when usernames and emails change.
- Prefer standard discovery endpoints over hardcoded magic strings where possible.
┌──────────┐ ┌──────────────┐ ┌───────────────┐ │ Browser │───▶│ Identity IdP │───▶│ App callback │ └──────────┘ └──────────────┘ └───────────────┘ │ │ │ └──── code ───────┴── token exchange ──┘
3) JWTs, sessions, and token hygiene¶
JWTs are portable containers. They are not magical trust dust.
Stateless validation helps when many services must verify tokens without central session reads.
But revocation becomes harder when claims live too long and spread too widely.
Server-side sessions still win in many web apps because logout and rotation stay simpler.
See. Choose the boring option when it removes risk without hurting the product.
- Keep claims minimal: subject, issuer, audience, expiry, and only needed scopes.
- Do not stuff role history, profile blobs, and tenant settings into every access token.
- Use short-lived access tokens and tighter handling for refresh tokens.
- Bind refresh token use to client class, device posture, or session metadata.
- Rotate signing keys with overlap windows so older tokens can expire gracefully.
-
Document how clock skew is handled across distributed services.
-
Opaque sessions help when central revocation and simple logout matter most.
- JWT access tokens help when many resource servers need local verification.
- Either way, storage location matters as much as token format.
4) MFA, session management, and recovery¶
MFA is a risk reduction layer, not a magical shield against every takeover path.
Require stronger proof for admin actions, payroll access, tenant exports, or billing changes.
Phishing-resistant factors such as passkeys or hardware keys reduce replay and fake-prompt attacks.
Recovery flows deserve the same design energy as login flows because attackers target the easier path.
Now watch. A help-desk reset that skips verification can quietly cancel your proud MFA story.
- Expire idle sessions separately from absolute session lifetime.
- Allow session revocation after password reset, device loss, or suspected theft.
- Log impossible travel, repeated failures, strange device changes, and token reuse.
- Ask whether remembered devices are bounded by time, risk, and geography.
- Protect backup codes like credentials because they are credentials.
- Test account recovery with the same red-team energy used on login pages.
5) Implementation checklist and sharp edges¶
Good authentication feels boring in production. That is a compliment, not an insult.
The sharp edges usually hide in defaults, fallback paths, and third-party integration assumptions.
See. If one reverse proxy can inject identity headers, write down exactly why that stays safe.
Do not let your API accept unsigned user identity from the network edge without hard proof.
Token expiry, rotation, revocation, and observability should be visible in runbooks before launch.
- Name the issuer for each token and who owns its signing keys.
- State where secrets for signing or session encryption are stored.
- Define how logout behaves for browser tabs, mobile clients, and background jobs.
- List which claims are trusted by each downstream service.
- Write an incident step for key compromise and token replay detection.
- Review whether tenant switching changes identity, session, or only authorization context.
Every refresh path needs rate limits and anomaly checks.
Identity proof strength should match action sensitivity, not developer convenience.
Third-party SDK defaults must be read, not worshipped.
A broken logout story becomes a security story during incidents.
Silent token refresh deserves the same threat review as visible login.
Your incident runbook should say who can revoke sessions at scale.
Browser login and API login may share identity, but not always the same mechanics.
A subject identifier should survive email renames and branding changes.
Service-to-service identity should avoid shared static secrets when possible.
Token format is a distribution detail. Trust proof is the real story.
Where this lives in the wild¶
- SaaS products offering Google login, Microsoft login, and enterprise SAML SSO.
- Mobile apps using PKCE with an external identity provider.
- Internal admin panels that require MFA before sensitive operations.
- Microservice platforms validating workload tokens at every hop.
- B2B products mapping one corporate directory to many internal apps.
Pause and recall¶
- Why does OIDC exist on top of OAuth 2.0?
- When would a server session beat a JWT for simplicity?
- Why is refresh token handling more sensitive than access token handling?
- How can a strong MFA design still fail during account recovery?
Interview Q&A¶
Q: When should you prefer opaque sessions over JWT access tokens? A: Prefer opaque sessions when central revocation, simple logout, and server-rendered apps matter more than service-to-service portability. Common wrong answer to avoid: "JWT is always better because stateless means scalable."
Q: What does OIDC add to OAuth 2.0? A: OIDC standardizes identity claims, ID tokens, discovery, and user information so clients can verify who authenticated. Common wrong answer to avoid: "OIDC is just a different name for OAuth login."
Q: What should you validate on a JWT before trusting it? A: Validate signature, issuer, audience, expiry, not-before time, and sometimes token binding context. Common wrong answer to avoid: "If the token decodes correctly, it is fine."
Q: Why is MFA not enough by itself? A: Because phishing, weak recovery, session theft, and help-desk bypasses can still defeat the control chain. Common wrong answer to avoid: "MFA means account takeover is solved."
Apply now (5 min)¶
Sketch your product login flow in five boxes: user, app, IdP, token store, and protected API.
Write the exact token type in each hop.
Then mark where expiry, revocation, MFA, and logging happen.
If any box says handled magically, stop there and replace magic with a real component.
Bridge. Identity proven. But what CAN this identity do? → 02