0
0
HLDsystem_design~7 mins

API authentication (OAuth, JWT, API keys) in HLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
APIs exposed to the internet face risks of unauthorized access, data breaches, and misuse. Without a robust authentication mechanism, attackers can impersonate users or services, leading to data theft, service disruption, or unauthorized actions.
Solution
API authentication ensures that every request comes from a verified source by requiring credentials or tokens. OAuth delegates user authorization securely without sharing passwords, JWT provides a compact token that carries user identity and claims, and API keys offer a simple secret token to identify and control client access.
Architecture
Client App
(User Agent)
API Gateway
Auth Provider
Auth Provider

This diagram shows a client requesting access through an API Gateway that verifies authentication tokens with an Auth Provider before forwarding requests to the backend.

Trade-offs
✓ Pros
OAuth allows secure delegated access without exposing user credentials.
JWT tokens are stateless, reducing server load by avoiding session storage.
API keys are simple to implement and easy to distribute for service-to-service calls.
✗ Cons
OAuth flows can be complex to implement and require careful token management.
JWT tokens, if not properly secured, can be intercepted and reused (replay attacks).
API keys lack fine-grained user identity and are vulnerable if leaked.
Use OAuth when user consent and delegated access are needed, JWT for scalable stateless authentication in distributed systems, and API keys for simple service authentication or internal APIs.
Avoid OAuth for simple internal services without user context, JWT when token revocation is critical and complex, and API keys for public APIs exposed to untrusted clients.
Real World Examples
Google
Uses OAuth 2.0 to allow third-party apps to access user data securely without sharing passwords.
Netflix
Uses JWT tokens to authenticate users across distributed microservices without centralized session storage.
Stripe
Uses API keys to authenticate service-to-service API calls securely and track usage.
Alternatives
Basic Authentication
Sends username and password with each request encoded in base64 without token exchange.
Use when: Use only for simple, low-risk internal APIs or during early development phases.
Session-based Authentication
Stores user session state on the server and uses cookies to maintain authentication.
Use when: Choose when server-side session control and easy token revocation are priorities.
Summary
API authentication prevents unauthorized access by verifying client identity using tokens or keys.
OAuth, JWT, and API keys each serve different use cases balancing security, complexity, and scalability.
Choosing the right method depends on user context, system scale, and security requirements.