How OAuth 2.0 Works: The Valet Key Pattern
Stop sharing your password. OAuth 2.0 lets you grant limited access to your data (like 'Read Contacts') without sharing your credentials.
Abstract AlgorithmsTLDR: OAuth 2.0 is an authorization protocol. It lets a third-party app (like Spotify) access your resources (like Facebook Friends) without you giving it your Facebook password. It uses short-lived Access Tokens as scoped, revocable keys.
π The Valet Key Pattern: Access Without Passwords
Your car has two keys:
- Master Key: Opens doors, starts engine, opens trunk and glovebox. (Your Password.)
- Valet Key: Starts the engine and unlocks only the door. Cannot open the trunk. (Access Token.)
You hand the Valet Key to the parking attendant (Third-Party App). They park the car (do the job) but can't steal the contents of the trunk (access your private data).
This is OAuth 2.0 in one sentence: grant limited, temporary access without sharing your password.
π’ The Four Roles Every OAuth Flow Has
| Role | Who It Is | Example |
| Resource Owner | You, the user | The person who owns the Facebook account |
| Client | The app requesting access | Spotify |
| Authorization Server | The identity guard | Facebook Login (accounts.facebook.com) |
| Resource Server | The API holding your data | Facebook Graph API |
The Client never sees your password. It only gets a token from the Authorization Server after you approve the request.
βοΈ The Authorization Code Flow: Step by Step
This is the most secure and most common grant type. Used whenever the Client is a server-side web app.
sequenceDiagram
participant U as User (Browser)
participant C as Client (Spotify)
participant AS as Auth Server (Facebook)
participant RS as Resource Server (FB API)
U->>C: "Login with Facebook"
C->>AS: Redirect: GET /authorize?client_id=...&scope=email
AS->>U: Show consent screen: "Spotify wants your email. Allow?"
U->>AS: Clicks Allow
AS->>C: Redirect back with ?code=AUTH_CODE
Note over C,AS: Server-to-server β user never sees this
C->>AS: POST /token {code, client_secret}
AS->>C: { access_token, refresh_token, expires_in }
C->>RS: GET /me/email Authorization: Bearer ACCESS_TOKEN
RS->>C: { email: "you@example.com" }
Why the extra step (Code β Token)?
The Auth Code appears in the browser's URL bar β visible in logs and history. The actual Access Token is exchanged server-to-server where the user/browser never sees it. This prevents token theft via browser history or referrer headers.
π§ Access Tokens, Refresh Tokens, and Scopes
Scopes: Limiting What the Token Can Do
When Spotify redirects you to Facebook, it requests specific scopes:
GET /authorize?scope=email+read_friends
The consent screen shows exactly what Spotify is asking for. You can approve or deny. The token is limited to those scopes β Spotify cannot suddenly read your photos.
Token Lifetimes
| Token | Typical Lifetime | Purpose |
| Access Token | 1 hour | Short-lived bearer credential for API calls |
| Refresh Token | 30β90 days | Exchange for a new Access Token without user interaction |
| Auth Code | 10 minutes | One-time use; expires after the Token exchange |
Refresh Without Re-Login
Client β POST /token { grant_type=refresh_token, refresh_token=... }
Auth Server β new Access Token
The user stays "logged in" without re-approving. The Refresh Token itself is rotated on use in modern implementations (rotation prevents replay attacks).
βοΈ Choosing the Right Grant Type
| Scenario | Grant Type | Why |
| Web app with server backend | Authorization Code | Most secure; token never in browser |
| Single-page app (no backend) | Auth Code + PKCE | Replaces client_secret with PKCE verifier |
| Machine-to-machine (no user) | Client Credentials | Service authenticates with its own client_id + secret |
| Highly trusted first-party app | Resource Owner Password | Direct username/password; avoid if possible |
PKCE (Proof Key for Code Exchange): Used for public clients (mobile apps, SPAs) that cannot safely store a client_secret. The client generates a code_verifier and code_challenge pair β the server verifies the proof without needing a pre-shared secret.
OAuth 2.0 vs OpenID Connect
OAuth 2.0 answers: "Can this app access this resource?"
OpenID Connect (OIDC) adds: "Who is this user?" β it returns an ID Token (JWT) with the user's identity alongside the access token. Most "Login with Google" buttons use OIDC on top of OAuth 2.0.
π‘οΈ Common Security Pitfalls
| Pitfall | Why It Matters | Mitigation |
| Token in URL fragment | Visible in browser history and server logs | Always exchange Auth Code server-side |
Missing state parameter | Enables CSRF attacks during the redirect | Generate and validate a random state nonce |
| Long-lived access tokens | Stolen tokens stay valid longer | Short expiry (1h) + refresh token rotation |
| Overly broad scopes | Exposes more data than needed | Request minimum scopes; show clear consent |
π Summary
- OAuth 2.0 = authorization, not authentication. "Can Spotify see my email?" not "Is this Spotify?"
- Authorization Code Flow: redirect β consent β code β server-side token exchange β access token.
- Access Tokens are scoped and short-lived; Refresh Tokens allow silent renewal.
- PKCE replaces
client_secretfor public clients (SPAs, mobile apps). - OpenID Connect adds identity (
id_token) on top of OAuth 2.0.
π Practice Quiz
Why does the Authorization Code Flow use a two-step code-then-token exchange instead of returning the token directly?
- A) To make the flow longer for security theater.
- B) The code appears in the browser URL (visible); the token is exchanged server-to-server (private).
- C) The token is too large for a URL parameter.
Answer: B
What stops Spotify from using your Facebook access token to also read your private photos?
- A) OAuth tokens are encrypted per-app.
- B) Scopes: the token only grants the permissions explicitly approved by you during the consent step.
- C) Facebook rate-limits Spotify.
Answer: B
You're building a mobile app that can't safely store a client_secret. Which OAuth feature do you use?
- A) Client Credentials grant.
- B) PKCE (Proof Key for Code Exchange).
- C) Resource Owner Password grant.
Answer: B

Written by
Abstract Algorithms
@abstractalgorithms
More Posts
SFT for LLMs: A Practical Guide to Supervised Fine-Tuning
TLDR: Supervised fine-tuning (SFT) is the stage where a pretrained model learns task-specific response behavior from curated input-output examples. It is usually the first alignment step after pretraining and often the foundation for later RLHF. Good...
RLHF in Practice: From Human Preferences to Better LLM Policies
TLDR: Reinforcement Learning from Human Feedback (RLHF) helps align language models with human preferences after pretraining and SFT. The typical pipeline is: collect preference comparisons, train a reward model, then optimize a policy (often with KL...
PEFT, LoRA, and QLoRA: A Practical Guide to Efficient LLM Fine-Tuning
TLDR: Full fine-tuning updates every model weight, which is expensive in memory, compute, and storage. PEFT methods update only a small trainable slice. LoRA learns low-rank adapters on top of frozen base weights. QLoRA pushes efficiency further by q...
LLM Model Naming Conventions: How to Read Names and Why They Matter
TLDR: LLM names encode practical decisions: model family, size, training stage, context window, format, and quantization level. If you can decode naming conventions, you can avoid costly deployment mistakes and choose the right checkpoint faster. οΏ½...
