Design a Secure User Registration and Authentication Service
System DesignModel answerLast updated
Architect an in-house email/password signup and login system emphasizing secure password storage, API contract design, session state management, and edge-case handling.
Design an internal authentication microservice supporting primary email and password registration and login functionality. Third-party identity frameworks (such as OAuth2, OIDC, or social authenticators) are out of scope. High-concurrency distributed scaling is not required—assume a single monolithic database instance is sufficient—but your architectural design must prioritize robust API modeling, clean database normalization, secure credential handling, and reliable session control.
Key Focus Areas
- Core Requirements: Functional endpoints for account creation, credential validation, session retrieval, and explicit logout.
- Data Persistence: Database schemas, key fields, constraints, and relational mappings.
- Credential Protection: Hashing algorithms, salting techniques, memory hardness, and timing attack defenses.
- Session Lifecycle: Trade-offs between opaque server-managed tokens and stateless tokens (JWTs), including expiration, storage mechanisms, and revocation strategies.
- Input Validation & Security Edge Cases: Password policies, anti-enumeration tactics, rate-limiting, and concurrent registration race conditions.
System Assumptions & Constraints
- Infrastructure: All HTTP traffic is protected via TLS terminating upstream (e.g., at a load balancer or ingress proxy).
- Scope Limitations: Advanced identity workflows—such as MFA enforcement, password recovery links, email verification tokens, and account deletion protocols—can be treated as out of scope, provided your architecture indicates where they cleanly integrate.
Hints
Hint 1
Consider how database-level constraints handle race conditions during simultaneous user registration with identical email addresses.
Hint 2
Evaluate the operational trade-offs of storing sessions in a database (opaque tokens) versus relying on self-contained signed payloads (JWTs), especially around revocation.
Hint 3
Ensure password hashing algorithms are chosen specifically for computational and memory hardness (e.g., Argon2id or bcrypt) rather than throughput speed (e.g., SHA-256).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & System Scope
Functional Requirements
- User Registration: Create a user record using a unique normalized email and password.
- User Authentication (Login): Verify credentials and issue an authenticated session payload upon successful validation.
- Session Verification: Authenticate subsequent API calls via incoming session credentials.
- Logout: Invalidate an active session across single or all active devices.
Out-of-Scope (Integration Points Noted)
- Email Verification: Can be added via an unverified account status flag and a short-lived token generated during registration.
- Multi-Factor Authentication (MFA): Can be integrated as a post-password challenge step in the authentication pipeline.
- Password Reset: Can be supported via single-use, time-bound reset tokens dispatched over email.
Non-Functional & Security Constraints
- Transport Security: TLS 1.3 assumed at the edge proxy.
- Credential Resilience: Resistance to dictionary, rainbow table, timing, and credential stuffing attacks.
- Storage: Relational store (e.g., PostgreSQL) with low-latency lookup capability.
2. API Contract Design
A. User Registration
POST /v1/auth/register
- Request Body:
{ "email": "[email protected]", "password": "CorrectHorseBatteryStaple123!" } - Responses:
201 Created: Account successfully created. Returns user metadata and issues an initial session cookie/token.{ "user": { "id": "usr_9j2f8x1a", "email": "[email protected]", "created_at": "2025-01-15T10:00:00Z" } }400 Bad Request: Payload validation failure (e.g., invalid email format, weak password).409 Conflict: Account with this email already exists (or200 OKwith generic feedback if strict privacy/anti-enumeration is enforced).
B. User Authentication
POST /v1/auth/login
- Request Body:
{ "email": "[email protected]", "password": "CorrectHorseBatteryStaple123!" } - Responses:
200 OK: Sets secure cookieSet-Cookie: session_token=...; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=604800(or returns bearer token in body).401 Unauthorized: Invalid credentials (generic message to prevent user enumeration).429 Too Many Requests: Rate limit exceeded for IP or email address.
C. Get Current User Profile
GET /v1/auth/me
- Headers:
Authorization: Bearer <opaque_token>OR sent automatically viaHttpOnlycookie. - Responses:
200 OK: User details payload.401 Unauthorized: Session token is invalid, expired, or revoked.
D. User Logout
POST /v1/auth/logout
- Query / Payload Params: Optional
?all_devices=trueflag. - Responses:
204 No Content: Session(s) successfully cleared/invalidated.
3. Data Schema
To handle relational integrity, user identity, and session invalidation efficiently, we use two primary tables:
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) NOT NULL UNIQUE,
email_canonical VARCHAR(255) NOT NULL UNIQUE, -- Lowercase & trimmed for lookup
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE user_sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(64) NOT NULL UNIQUE, -- SHA-256 hash of the session token
ip_address INET,
user_agent TEXT,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
revoked BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX idx_sessions_token_hash ON user_sessions(token_hash) WHERE revoked = FALSE;
CREATE INDEX idx_sessions_user_id ON user_sessions(user_id);
Schema Highlights:
- Canonical Email: Converts inputs (e.g.,
[email protected]$\rightarrow$[email protected]) to prevent duplicate accounts via case variations. - Database Unique Constraint: Enforces uniqueness at the storage layer to prevent race conditions during concurrent account creations.
- Token Hashing: Opaque session tokens are hashed with SHA-256 prior to storage. If the session table is compromised, active session identifiers cannot be hijacked.
4. Credential Storage & Security Design
+------------------+ +-------------------------------+ +----------------------+
| Plaintext Pass | --> | Argon2id Hashing Function | --> | Stored Hash String |
| "MySecretPass" | | Params: Salt, m=64MB, t=3, p=4| | "$argon2id$v=19$..." |
+------------------+ +-------------------------------+ +----------------------+
Hashing Strategy
- Algorithm Choice: Use modern, memory-hard key derivation functions like Argon2id (or bcrypt / scrypt if Argon2id is not supported by legacy bindings). Fast cryptographic hashes (SHA-256, MD5) are vulnerable to GPU-based hardware brute-force attacks.
- Salting: Generate a cryptographically secure random 16-byte salt per user. Argon2id embeds salt and parameter configurations directly into the output hash string format.
- System Pepper (Optional): Maintain a server-side secret key (stored in a hardware security module or secure environment configuration) appended/HMAC-ed to the password before hashing. This adds defense-in-depth against offline hash cracking if the database is leaked.
Preventing Timing Attacks
- Constant-Time Validations: Verification operations must execute in constant time (
crypto/subtleor equivalent library constructs). - Dummy Computations: If a user login attempt provides an unpopulated or non-existent email, execute a standard dummy Argon2id verification using a pre-calculated dummy hash. This masks the difference in compute timing between existing and non-existing accounts.
5. Session State Management
| Feature Strategy | Opaque Server-Side Tokens | Stateless JWT (JSON Web Tokens) |
|---|---|---|
| Storage Mechanism | Cryptographically secure random bytes stored in Database/Redis. | Cryptographically signed, client-stored payload. |
| Revocation | Immediate. Simple setting of revoked = true or key deletion. | Difficult. Requires maintaining distributed denial-lists/blacklists until expiry. |
| Database Overhead | Requires a storage read query per authenticated request. | Zero database lookup required for identity parsing. |
| Best Used For | Web apps, sensitive operations, stateful sessions. | Scalable microservice inter-service delegation, short-lived tokens. |
Recommended Design for this Architecture: Opaque Server-Side Tokens.
- Token Generation: Upon successful authentication, the server generates a 32-byte cryptographically random string (e.g., using
crypto/rand). - Storage: The server stores
SHA-256(token)in theuser_sessionstable and sets the raw token in an HTTP cookie. - Cookie Attributes:
HttpOnly: Prevents client-side JavaScript access (mitigates XSS token theft).Secure: Restricts transmission strictly over encrypted HTTPS channels.SameSite=Strict: Prevents cross-site request forgery (CSRF) vectors.
6. Edge Cases, Validation, and Rate Limiting
A. Concurrency & Race Conditions
- Issue: Two concurrent signup requests with the same email could pass an application-level check before insertion.
- Resolution: Rely on the
UNIQUEdatabase index constraint onemail_canonical. The application catches the database unique constraint violation and returns a proper duplicate user conflict error.
B. Anti-Enumeration Protocols
- Login: Always return a generic error message: "Invalid email or password".
- Timing Normalization: Ensure the computational duration of non-existent user login evaluations matches valid user processing times through fake hash calculations.
C. Rate-Limiting & Brute Force Prevention
- IP-Based Throttling: Limit requests to
/v1/auth/loginto max 10 requests per minute per IP address. - Account-Based Throttling: Track failed attempts against a specific canonical email. After 5 consecutive failures, trigger exponential backoff or temporarily block login for that email account (e.g., 15-minute cooldown) while returning generic credentials errors to obscure account state.