Mental model
OAuth2 PKCE (Proof Key for Code Exchange) secures client authentication without exposing client secrets, while JWT (JSON Web Tokens) provides stateless, cryptographically signed authorization payloads across microservices.
Theory
- OAuth2 PKCE: Prevents authorization code injection attacks by requiring a dynamic
code_verifiermatching the pre-hashedcode_challenge. - JWT (Header.Payload.Signature): Stateless tokens signed using asymmetric cryptography (RS256/ES256). API gateways and services verify signatures using Public Keys (
JWKSendpoint) without querying database sessions.
Alternatives and trade-offs
- Stateful Session Cookies: Centralized revocation on server DB; requires database session lookups on every API request.
- Stateless JWT Tokens: Fast distributed validation via public keys; immediate token revocation requires maintaining a Redis token revocation blocklist (JTI).
Failure modes and misconceptions
- Symmetric Secret Key Insecurity: Using HS256 (shared secret) forces microservices to hold the private secret key to verify tokens. Use RS256/ES256 asymmetric keys so services only require public keys.
- Missing Token Expiration (
exp): Issuing JWT tokens without strictexpclaims allows stolen tokens to grant access indefinitely.
Decision scenario
Implement OAuth2 PKCE with RS256-signed JWT access tokens for single-page applications (SPAs) and mobile clients to ensure secure authentication without embedded secrets.
Learning outcomes
- Structure OAuth2 PKCE authorization flows for public client applications.
- Verify JWT signatures asynchronously using public key sets (JWKS).
- Enforce role-based access scopes in FastAPI dependency injection pipelines.
Trade-offs
Stateless JWT tokens enable high-speed distributed verification, but require short TTLs and revocation lists to handle compromised accounts.