Demystifying OAuth 2.0 and OpenID Connect
OAuth 2.0 and OIDC are the foundation of modern authentication and authorization. Cut through the jargon—grants, flows, tokens, scopes—with clear explanations and when-to-use guidance.
# Demystifying OAuth 2.0 and OpenID Connect OAuth 2.0 and OpenID Connect (OIDC) are frequently confused, conflated, or misimplemented. Let's build a clear mental model from the ground up. ## OAuth 2.0: Authorization, Not Authentication OAuth 2.0 is a **delegation protocol**. It lets a user grant a third-party application limited access to their resources *without sharing their password*. Key roles: - **Resource Owner** – The user - **Client** – The application requesting access - **Authorization Server** – Issues tokens (e.g., Auth0, Keycloak) - **Resource Server** – The API protecting the resources ## The Authorization Code Flow (PKCE) The safest flow for server-side and SPA apps: ``` 1. User clicks "Login with Google" 2. App redirects to Google with: client_id, redirect_uri, scope, code_challenge 3. User authenticates and consents 4. Google redirects back with: ?code=AUTH_CODE 5. App exchanges code + code_verifier for: access_token, refresh_token 6. App calls API with: Authorization: Bearer ACCESS_TOKEN ``` Always use PKCE (Proof Key for Code Exchange), even for server-side apps. ## Tokens | Token | Format | Purpose | Lifespan | |---|---|---|---| | Access Token | JWT or opaque | Authorize API calls | Short (15m–1h) | | Refresh Token | Opaque | Get new access tokens | Long (days–weeks) | | ID Token | JWT | Authenticate the user (OIDC) | Short | ## OpenID Connect: Authentication on Top of OAuth OIDC adds an **ID token** and a `/userinfo` endpoint to OAuth 2.0. While OAuth says "you can access these resources," OIDC says "here's *who* the user is." If you need to know **who logged in**, use OIDC. If you only need to **access an API**, use OAuth 2.0. ## Common Mistakes - Using the **Implicit flow** (deprecated; use Authorization Code + PKCE) - Treating the **access token as authentication** (verify the ID token for that) - Storing tokens in **localStorage** (use httpOnly cookies for refresh tokens) - Not validating **token signatures and expiry** on the server Implement OAuth/OIDC with a battle-tested library—never roll your own.
