#25 Security/OAuth2/JWT
Login & Auth System
Sign users in safely, keep them signed in across services, and let third-party apps act for them without seeing their password.
What is being asked
Design authentication for a large product: registration, password and social login, multi-factor, sessions, and a way for many backend services to trust a request.
Requirements
Functional
- Sign up, sign in, sign out, password reset, multi-factor authentication.
- Single sign-on across the company's applications.
- Delegated access for third-party apps.
Non-functional
- Passwords and tokens must be safe even if a database leaks.
- Verifying a request must be fast, on every call.
- Resist guessing, credential stuffing and token theft.
Design
- Passwords are stored only as slow, salted hashes (Argon2 or bcrypt). Sign-in compares hashes and then asks for a second factor where enabled.
- The auth service issues a short-lived access token, a signed JWT valid for minutes, and a long-lived refresh token stored server-side.
- Services verify the access token's signature with the auth service's public key, with no network call.
- When the access token expires, the client exchanges the refresh token for a new pair. Refresh tokens are rotated: each is used once.
- Third-party apps use OAuth 2 authorisation code flow with PKCE and receive tokens limited to the scopes the user approved.
Key decisions and trade-offs
- Stateless tokens or server sessions. JWTs verify locally and scale, but cannot be revoked before they expire. Short lifetimes plus revocable refresh tokens is the standard compromise.
- Where the browser keeps tokens. An HttpOnly, Secure, SameSite cookie is safe from script theft; local storage is exposed to any cross-site scripting bug.
- Rate limiting and lockout. Limit attempts per account and per address, and prefer delays to hard lockouts that attackers can use to lock users out.
- Refresh-token reuse is a theft signal: revoke the whole family when an already-used token appears.
Follow-up questions
- How do you sign a user out of every device immediately?
- How would you rotate the signing key without logging everyone out?
- How do you defend against a list of leaked passwords being tried on your site?
- What goes into the JWT, and what should never be put there?