Design API authentication for a platform serving both first-party clients (your own SPA/mobile) and third-party integrations (partner API consumers).
Key Talking Points
- ✓First-party user-facing clients: use OAuth 2.0 Authorization Code flow with PKCE (no client secret in the browser/mobile app). Access tokens short-lived (5–15 min), refresh tokens long-lived stored in HttpOnly cookies or secure storage. Never use the Implicit flow (deprecated — tokens in fragment, no refresh).
- ✓Third-party server-to-server (machine-to-machine): use OAuth 2.0 Client Credentials flow. Partners authenticate with a `client_id` + `client_secret` and receive a short-lived access token scoped to only the APIs they need. No user involved.
- ✓API keys as an alternative for simple integrations: generate cryptographically random keys (≥128 bits), store only the hash server-side (SHA-256), show the raw key once at creation. Scope keys to specific operations; support key rotation and revocation.
- ✓mTLS (mutual TLS) for high-assurance machine-to-machine: both client and server present certificates. Strongest option — the client's identity is cryptographically proven at the transport layer, not via a bearer token that can be stolen.
- ✓Token scopes and least privilege: every token should carry only the minimum scopes required. The authorization server must enforce scopes — the resource server must validate them on every request.
- ✓Token validation at the API gateway: verify signature, `iss`, `aud`, `exp`, and `scope` on every request. Reject tokens with unexpected algorithms. Use a JWKS endpoint (cached, with rotation) for signature verification.
- ✓Rate limit per client_id (not just per IP) and log all auth failures. Revocation: access tokens expire quickly; refresh tokens and API keys need an explicit revocation list.
First-party and third-party clients have different trust levels and different auth flows. First-party clients use the user's session (Authorization Code + PKCE for SPAs/mobile); third-party clients use machine-to-machine credentials (client credentials, API keys, or mTLS) with explicit scopes.