How do you implement OAuth 2.0 and API authentication patterns?
OAuth 2.0 is the standard protocol for API authorization, enabling third-party access without sharing credentials. Flows: (1) Authorization Code (with PKCE): for web and mobile apps. Client redirects user to auth server, user authenticates and consents, auth server returns authorization code to client, client exchanges code for access token. PKCE (Proof Key for Code Exchange) prevents code interception attacks and is required for public clients. (2) Client Credentials: for server-to-server communication. Client authenticates directly with clientid and clientsecret to obtain an access token. No user involvement. (3) Device Code: for devices without browsers (smart TVs, CLI tools). Device displays a code, user enters it on another device to authorize. Token types: access tokens (short-lived, 15-60 minutes, used in API requests via Authorization: Bearer header), refresh tokens (long-lived, used to obtain new access tokens without re-authentication), and ID tokens (JWT containing user identity claims, used for authentication not authorization). JWT (JSON Web Token): self-contained tokens signed with RS256 or HS256, containing claims (sub, exp, iss, aud, scope). Verification: check signature validity, expiration (exp), issuer (iss), audience (aud), and required scopes. API key authentication: simpler alternative for server-to-server communication, sent via header (X-API-Key) or query parameter, suitable when OAuth complexity is unnecessary. Implement key rotation, per-key rate limiting, and key-level permissions. Security: implement token storage securely (HTTP-only cookies for web, secure storage for mobile), implement token rotation (new refresh token with each use), log all authentication events, and implement token revocation for compromised credentials.