All Posts

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 AlgorithmsAbstract Algorithms
Β·Β·5 min read
Share
Share on X / Twitter
Share on LinkedIn
Copy link

TLDR: 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

RoleWho It IsExample
Resource OwnerYou, the userThe person who owns the Facebook account
ClientThe app requesting accessSpotify
Authorization ServerThe identity guardFacebook Login (accounts.facebook.com)
Resource ServerThe API holding your dataFacebook 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

TokenTypical LifetimePurpose
Access Token1 hourShort-lived bearer credential for API calls
Refresh Token30–90 daysExchange for a new Access Token without user interaction
Auth Code10 minutesOne-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

ScenarioGrant TypeWhy
Web app with server backendAuthorization CodeMost secure; token never in browser
Single-page app (no backend)Auth Code + PKCEReplaces client_secret with PKCE verifier
Machine-to-machine (no user)Client CredentialsService authenticates with its own client_id + secret
Highly trusted first-party appResource Owner PasswordDirect 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

PitfallWhy It MattersMitigation
Token in URL fragmentVisible in browser history and server logsAlways exchange Auth Code server-side
Missing state parameterEnables CSRF attacks during the redirectGenerate and validate a random state nonce
Long-lived access tokensStolen tokens stay valid longerShort expiry (1h) + refresh token rotation
Overly broad scopesExposes more data than neededRequest 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_secret for public clients (SPAs, mobile apps).
  • OpenID Connect adds identity (id_token) on top of OAuth 2.0.

πŸ“ Practice Quiz

  1. 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
  2. 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
  3. 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

Abstract Algorithms

Written by

Abstract Algorithms

@abstractalgorithms