MongoDB
Designing an Authentication System
Build a secure, scalable authentication system covering JWT, OAuth 2.0, refresh tokens, MFA, and session management.
S
srikanthtelkalapally888@gmail.com
Designing an Authentication System
Authentication verifies identity. Authorization controls what authenticated users can do.
Authentication Methods
JWT (JSON Web Tokens)
Header.Payload.Signature
Payload: { user_id: 123, role: 'admin', exp: 1700000000 }
Pros: Stateless, scalable Cons: Cannot invalidate before expiry
Session Tokens
Session ID stored in cookie
Server-side session in Redis
Pros: Immediate invalidation Cons: Requires session store
Access + Refresh Token Pattern
Access Token: Short-lived (15 min) → API calls
Refresh Token: Long-lived (30 days) → Get new access token
Flow:
1. Login → Get access_token + refresh_token
2. API call with access_token
3. Access expired → Use refresh_token to get new access_token
4. Logout → Invalidate refresh_token
OAuth 2.0 Flows
- Authorization Code: Web apps (most secure)
- Client Credentials: Service-to-service
- Implicit: Deprecated
Multi-Factor Authentication (MFA)
Factor 1: Password (something you know)
Factor 2: TOTP (Google Authenticator) or SMS OTP
TOTP: TOTP = HMAC(secret, floor(time/30))
Password Storage
NEVER store plain passwords.
hash = bcrypt(password, saltRounds=12)
Use bcrypt, Argon2, or scrypt.
Security Best Practices
- HTTPS everywhere
- HTTP-only cookies for tokens
- Rotate refresh tokens on use
- Rate limit login endpoints
Conclusion
JWT + refresh tokens is the modern standard. Add MFA for sensitive applications and always use bcrypt for password hashing.