OAuth2 and JWT are everywhere. If you're building APIs in 2020, you're probably using them. But there's a gap between "using OAuth2" and "doing OAuth2 right". The devil is in the details: how you design your tokens, which grant types you choose, how carefully you validate them. Get these wrong and you have something that looks secure but isn't.
OAuth2 grant types in context
OAuth2 provides multiple grant types for different client contexts. Authorization Code with PKCE: the correct grant for browser-based and mobile clients (no client secret on the frontend). Client Credentials: for service-to-service authentication where no user is involved. Implicit flow (deprecated): avoid, use Authorization Code with PKCE instead. Resource Owner Password Credentials: avoid for new systems, provides no security over sending passwords directly. The grant type selection determines the security properties of the authentication.
JWT design decisions
A JWT contains a header (algorithm, token type), payload (claims), and signature. The payload design decisions: use 'sub' for the user identifier (not email, which can change), include 'aud' (audience) to prevent token reuse across services, set a short 'exp' (expiry, 15-60 minutes for access tokens) to limit the window of compromised token validity, and include only the claims the resource server needs. Over-claiming (putting everything in the JWT) creates large tokens and inflexible authorisation.
Token validation correctness
JWT validation must verify: the signature (using the correct algorithm, reject 'none' algorithm regardless of what the token header says), the expiry ('exp' claim), the audience ('aud' claim matches the service), and the issuer ('iss' claim matches the expected identity provider). Missing any of these validations creates an exploitable security vulnerability. The OWASP JWT Security Cheat Sheet provides the complete validation checklist.
Refresh token rotation
Access tokens should be short-lived (minutes to an hour). Refresh tokens allow obtaining new access tokens without re-authentication. Refresh token rotation (issue a new refresh token with each use, invalidate the old one) limits the impact of refresh token theft: a stolen refresh token can only be used once before the legitimate holder's next use detects the compromise (two tokens from the same parent). Rotate refresh tokens and detect single-use violations.