OAuth

What is OAuth 2.0? How It Actually Works

OAuth lets your app access a user's data on another service without their password. Instead of entering credentials into your app, users log in at the service directly — and that service gives your app a limited-access token.

The parking valet analogy

Giving a parking valet your house key along with your car key would be stupid. Valet keys exist — they unlock the car but not the house, and some disable the trunk. OAuth is the valet key for APIs: limited access to specific resources, without exposing full credentials.

The authorization code flow (most common)

  1. Your app redirects the user to the auth server — with client_id, redirect_uri, scope, and a PKCE code challenge
  2. User logs in at the auth server — your app never sees their password
  3. Auth server redirects back to your app — with a short-lived authorization code in the URL
  4. Your app exchanges the code for tokens — POST to /token with the code and PKCE verifier
  5. Auth server returns access token and refresh token
  6. Your app uses the access token — in the Authorization header of API calls
// Step 1 — Redirect user
const authUrl = `https://auth.example.com/authorize?
  client_id=YOUR_CLIENT_ID&
  redirect_uri=https://yourapp.com/callback&
  response_type=code&
  scope=openid profile email&
  code_challenge=${challenge}&
  code_challenge_method=S256`;

window.location.href = authUrl;

// Step 4 — Exchange code for tokens (on callback)
const tokens = await fetch('https://auth.example.com/token', {
  method: 'POST',
  body: new URLSearchParams({
    grant_type: 'authorization_code',
    code: authorizationCode,
    redirect_uri: 'https://yourapp.com/callback',
    client_id: 'YOUR_CLIENT_ID',
    code_verifier: storedVerifier,
  })
}).then(r => r.json());

OAuth vs OpenID Connect

OAuth is authorization — "can this app access your data?" OpenID Connect (OIDC) adds authentication — "who are you?" — by adding an ID token to the OAuth flow. When you use "Sign in with Google," that is OIDC on top of OAuth.

Why PKCE exists

Authorization codes in the URL can be stolen by malicious browser extensions or apps. PKCE (Proof Key for Code Exchange) adds a verifier that proves the entity exchanging the code is the same one that started the flow. Required for SPAs and mobile apps.

Debug your OAuth errors → OAuthFixer