Understanding OAuth 2.0 Flow
You add "Sign in with Google" to an app, copy a snippet from a tutorial, and it works on localhost. Then you deploy, the provider throws redirect_uri_mismatch, and while fixing that you notice the access token is sitting in localStorage and nobody ever checks the state parameter. Most OAuth bugs I see aren't exotic. They come from picking the wrong flow or skipping one small check.
This post walks through the parts of OAuth 2.0 you actually touch: the four roles, which grant type to use, how Authorization Code + PKCE works step by step, Client Credentials for server-to-server calls, token storage and refresh, and the checks that keep the whole thing from leaking.
OAuth 2.0 is about authorization, not authentication. It lets an app access resources on a user's behalf, but it doesn't tell you who that user is. If you need login, you want OpenID Connect (OIDC), which sits on top of OAuth 2.0.
What Is OAuth 2.0?
Say a photo-printing app wants to read your Google Photos. Before OAuth, the only way to do that was to hand the app your Google password, which is a terrible idea: the app gets full access to your account and you can't revoke it without changing your password.
OAuth 2.0 fixes that with delegated access. Google issues the printing app a token with a limited scope (say, read-only photos), and your password never leaves Google. You can revoke the token whenever you like. OAuth 2.0 replaced OAuth 1.0, mostly by dropping the request-signing requirements and relying on TLS instead.
The Four Key Roles
- Resource Owner: The user who owns the data and can grant access to it
- Client: The application requesting access (the photo-printing app)
- Authorization Server: Issues access tokens after authenticating the user (Google's auth server)
- Resource Server: Hosts the protected resources (Google Photos API)
The four OAuth 2.0 roles and how they interact
OAuth 2.0 Grant Types
A "grant type" is just the flow a client uses to get an access token. Which one you pick depends on whether there's a user involved and whether your client can keep a secret.
| Grant Type | Best For | Status |
|---|---|---|
| Authorization Code + PKCE | Web apps, SPAs, mobile apps | ✅ Recommended |
| Client Credentials | Machine-to-machine (no user) | ✅ Recommended |
| Implicit | SPAs (legacy) | ⛔ Deprecated |
| Resource Owner Password | First-party apps only | ⛔ Deprecated |
| Device Authorization | Smart TVs, CLI tools | ✅ Supported |
The Implicit and Resource Owner Password Credentials grants are deprecated in OAuth 2.1. The Implicit flow exposes tokens in URLs where they can be stolen from browser history or referrer headers. Always use Authorization Code + PKCE instead.
Authorization Code Flow (with PKCE)
This is the flow you'll use for almost anything with a user in it. Server-rendered apps that can keep a client secret use it directly. SPAs and mobile apps can't keep a secret, so they add PKCE (Proof Key for Code Exchange), which stops someone who intercepts the authorization code from redeeming it. OAuth 2.1 recommends PKCE for every client, confidential ones included, so I just use it everywhere.
Step-by-Step: Authorization Code + PKCE
Generate PKCE Verifier and Challenge
The client generates a random code_verifier string and derives a code_challenge from it using SHA-256. This pair proves the auth request and token exchange come from the same client.
Redirect User to Authorization Server
The client redirects the user's browser to the authorization endpoint with the code_challenge, requested scopes, and a redirect_uri.
User Authenticates and Consents
The authorization server shows the user a login page and consent screen. After approval, it redirects back to the client with a short-lived authorization_code.
Exchange Code for Tokens
The client sends the authorization_code along with the original code_verifier directly to the token endpoint (server-to-server). The authorization server verifies the pair and returns access and refresh tokens.
Access Protected Resources
The client includes the access_token in API requests as a Bearer token in the Authorization header.
Authorization Code + PKCE flow, the recommended approach for all app types
Implementing PKCE in JavaScript
// Generate a cryptographically random code_verifier
function generateCodeVerifier() {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
// Derive code_challenge from verifier using SHA-256
async function generateCodeChallenge(verifier) {
const encoder = new TextEncoder();
const data = encoder.encode(verifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
}
// Build authorization URL and redirect
async function startOAuthFlow() {
const verifier = generateCodeVerifier();
const challenge = await generateCodeChallenge(verifier);
// Store verifier in sessionStorage (needed for token exchange)
sessionStorage.setItem('pkce_verifier', verifier);
const params = new URLSearchParams({
response_type: 'code',
client_id: 'YOUR_CLIENT_ID',
redirect_uri: 'https://yourapp.com/callback',
scope: 'read:profile read:email',
state: crypto.randomUUID(), // CSRF protection
code_challenge: challenge,
code_challenge_method: 'S256',
});
window.location.href = `https://auth.example.com/authorize?${params}`;
}
// On the redirect callback page
async function handleCallback() {
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const state = params.get('state');
const verifier = sessionStorage.getItem('pkce_verifier');
if (!code || !verifier) {
throw new Error('Missing code or verifier');
}
const response = await fetch('https://auth.example.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: 'https://yourapp.com/callback',
client_id: 'YOUR_CLIENT_ID',
code_verifier: verifier,
}),
});
const tokens = await response.json();
// { access_token, refresh_token, token_type, expires_in }
// Store tokens securely; httpOnly cookies are preferred
// Never store access tokens in localStorage
sessionStorage.removeItem('pkce_verifier');
return tokens;
}
Client Credentials Flow
Sometimes there's no user at all. A cron job pulling reports from an API, a queue worker calling a billing service, one microservice talking to another. That's what Client Credentials is for.
It's the simplest flow. The client sends its own client ID and secret to the token endpoint and gets an access token back. No redirect, no consent screen.
const axios = require('axios');
class OAuthClient {
constructor(clientId, clientSecret, tokenUrl) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.tokenUrl = tokenUrl;
this.token = null;
this.tokenExpiry = null;
}
async getAccessToken() {
// Return cached token if still valid (with 60s buffer)
if (this.token && Date.now() < this.tokenExpiry - 60000) {
return this.token;
}
const response = await axios.post(
this.tokenUrl,
new URLSearchParams({
grant_type: 'client_credentials',
scope: 'api:read api:write',
}),
{
auth: {
username: this.clientId,
password: this.clientSecret,
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}
);
this.token = response.data.access_token;
this.tokenExpiry = Date.now() + response.data.expires_in * 1000;
return this.token;
}
async callAPI(endpoint) {
const token = await this.getAccessToken();
return axios.get(endpoint, {
headers: { Authorization: `Bearer ${token}` },
});
}
}
// Usage
const client = new OAuthClient(
process.env.CLIENT_ID,
process.env.CLIENT_SECRET,
'https://auth.example.com/token'
);
const data = await client.callAPI('https://api.example.com/reports');
Cache the token until it's close to expiring. Fetching a new one on every API call adds a round trip and can get you rate limited by the authorization server. The example above refreshes 60 seconds before expiry. If you run several workers, consider a shared cache (Redis, for example) so each process isn't requesting its own token.
Understanding OAuth 2.0 Tokens
You'll deal with three kinds of tokens. They have different jobs and very different lifetimes.
Short-lived credential used to access protected resources. Typically expires in 15 minutes to 1 hour.
Usually a JWT (JSON Web Token) that the resource server can validate without calling the authorization server:
// Decoded access token (JWT)
{
"iss": "https://auth.example.com",
"sub": "user_12345",
"aud": "https://api.example.com",
"exp": 1746000000,
"iat": 1745996400,
"scope": "read:profile read:email",
"client_id": "my-app-client-id"
}
// Usage in API request
Authorization: Bearer eyJhbGciOiJSUzI1NiJ9...
The resource server validates the JWT signature using the authorization server's public key, so there's no network call per request.
Long-lived credential used exclusively to obtain new access tokens when the current one expires. Never sent to resource servers.
// Refresh token exchange
const response = await fetch('https://auth.example.com/token', {
method: 'POST',
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: storedRefreshToken,
client_id: 'YOUR_CLIENT_ID',
// client_secret required for confidential clients
}),
});
const { access_token, refresh_token } = await response.json();
// Note: authorization server may rotate the refresh token
// Always store the new one
Store refresh tokens securely. In web apps, use httpOnly cookies. In mobile apps, use the platform's secure storage (Keychain / Keystore).
OpenID Connect extension. When you request the openid scope, the authorization server also returns an ID Token. It's a JWT with identity claims about the user who just logged in.
// Decoded ID token
{
"iss": "https://auth.example.com",
"sub": "user_12345",
"aud": "my-app-client-id",
"exp": 1746000000,
"iat": 1745996400,
"name": "Jane Doe",
"email": "jane@example.com",
"picture": "https://example.com/jane.jpg",
"email_verified": true
}
// Verify ID token before trusting it
import { jwtVerify, createRemoteJWKSet } from 'jose';
const JWKS = createRemoteJWKSet(
new URL('https://auth.example.com/.well-known/jwks.json')
);
const { payload } = await jwtVerify(idToken, JWKS, {
issuer: 'https://auth.example.com',
audience: 'my-app-client-id',
});
Security Best Practices
The spec itself is fine. Most real OAuth problems come from implementations that skip a step. These are the ones I check first.
1. Always Use PKCE for Public Clients
Any client that can't keep a secret (SPAs, mobile apps, desktop apps) is a "public client." For these, PKCE isn't optional. Without it, a malicious app on the same device that registers the same custom URL scheme can grab the redirect and redeem the code itself.
2. Validate the State Parameter
// Before redirect: generate and store state
const state = crypto.randomUUID();
sessionStorage.setItem('oauth_state', state);
// In the authorization URL
const params = new URLSearchParams({
// ...
state,
});
// In the callback, validate state matches
function handleCallback() {
const returnedState = new URLSearchParams(window.location.search).get('state');
const savedState = sessionStorage.getItem('oauth_state');
sessionStorage.removeItem('oauth_state');
if (returnedState !== savedState) {
throw new Error('State mismatch: possible CSRF attack');
}
// Continue with token exchange...
}
3. Strict Redirect URI Validation
Register exact redirect URIs with your authorization server. No wildcards, no prefix matching. If the server accepts any URI under your domain, an attacker can point the redirect at a page they control (or an open redirect on your site) and collect authorization codes.
The flip side is the error everyone hits on their first deploy: redirect_uri_mismatch (or invalid_grant at the token endpoint). The comparison is a plain string match, so http vs https, a trailing slash, www., or a port number all count as different URIs. Also, the redirect_uri you send in the token request has to be identical to the one in the authorize request. Behind a load balancer or proxy that terminates TLS, check that your framework isn't building the callback URL with http://. In Laravel that usually means configuring trusted proxies.
4. Store Tokens Securely
| Storage Location | Access Token | Refresh Token | Verdict |
|---|---|---|---|
| localStorage | Accessible via JS | Accessible via JS | ⛔ XSS risk |
| sessionStorage | Cleared on tab close | Not recommended | ⚠️ Still XSS risk |
| httpOnly Cookie | Not readable by JS | Secure storage | ✅ Preferred for web |
| Memory (JS variable) | Lost on page refresh | Not practical | ✅ Acceptable for access tokens |
| Keychain / Keystore | N/A | OS-managed secure storage | ✅ Required for mobile |
5. Validate JWT Signatures Server-Side
import { createRemoteJWKSet, jwtVerify } from 'jose';
import { Request, Response, NextFunction } from 'express';
const JWKS = createRemoteJWKSet(
new URL('https://auth.example.com/.well-known/jwks.json')
);
export async function requireAuth(
req: Request,
res: Response,
next: NextFunction
) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing bearer token' });
}
const token = authHeader.slice(7);
try {
const { payload } = await jwtVerify(token, JWKS, {
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});
// Attach decoded claims to request
req.user = payload;
next();
} catch (err) {
return res.status(401).json({ error: 'Invalid or expired token' });
}
}
JWT payloads are base64url-encoded, not encrypted. Anyone can decode one and anyone can forge one. Don't trust a JWT you've only decoded. Verify the signature and check iss, aud, and exp. Skipping that check is one of the most common OAuth mistakes I come across.
Handling Token Refresh
Access tokens expire quickly on purpose. Your client should refresh them quietly in the background so the user isn't kicked back to the login page every hour. The tricky part is concurrency: if five requests fire at once with an expired token, you want one refresh, not five. That matters even more when the server rotates refresh tokens, because the second refresh would use a token that's already been invalidated.
class AuthClient {
#accessToken = null;
#refreshToken = null;
#tokenExpiry = null;
#refreshPromise = null; // Prevent concurrent refreshes
async fetch(url, options = {}) {
const token = await this.#getValidToken();
const response = await fetch(url, {
...options,
headers: {
...options.headers,
Authorization: `Bearer ${token}`,
},
});
// Handle token revocation mid-session
if (response.status === 401) {
this.#accessToken = null;
throw new Error('Session expired. Please log in again.');
}
return response;
}
async #getValidToken() {
// Token still valid with 30s buffer
if (this.#accessToken && Date.now() < this.#tokenExpiry - 30000) {
return this.#accessToken;
}
// Prevent concurrent refresh calls (race condition)
if (!this.#refreshPromise) {
this.#refreshPromise = this.#doRefresh().finally(() => {
this.#refreshPromise = null;
});
}
return this.#refreshPromise;
}
async #doRefresh() {
if (!this.#refreshToken) throw new Error('No refresh token available');
const res = await fetch('/auth/refresh', {
method: 'POST',
credentials: 'include', // Include httpOnly cookie with refresh token
});
if (!res.ok) throw new Error('Token refresh failed');
const data = await res.json();
this.#accessToken = data.access_token;
this.#tokenExpiry = Date.now() + data.expires_in * 1000;
return this.#accessToken;
}
}
When I'd Reach for OAuth (and When I Wouldn't)
OAuth earns its complexity when a third party is involved: you want users to log in with Google or GitHub, you're calling someone else's API on a user's behalf, or other teams' apps need scoped access to yours. It's also a reasonable fit when you have several first-party apps sharing one identity provider.
For a single Laravel or Node app with its own login form and its own frontend on the same domain, I usually wouldn't build an OAuth server. A plain session cookie (or Laravel Sanctum for an SPA on the same top-level domain) is simpler and has fewer moving parts to get wrong. Running your own authorization server means owning key rotation, consent screens, token revocation and audit logging. If you need it, a hosted provider or a maintained package like Laravel Passport is usually a better bet than writing one.
What to Check Before Going to Production
- Redirect URIs are registered exactly for each environment (staging and production are separate entries), with no wildcards
- State is checked on the callback, and the request fails loudly when it doesn't match
- No tokens in localStorage. Refresh tokens live in httpOnly, Secure cookies on the web, or Keychain/Keystore on mobile
- Scopes are minimal. Asking for more than you need makes the consent screen scarier and widens the damage if a token leaks
- Refresh token rotation is on if your provider supports it, and your client handles concurrent refreshes
- Clock skew: if
exp/iatvalidation fails intermittently, check NTP on your servers before blaming the library
OAuth 2.0 vs OpenID Connect: Quick Reference
| Aspect | OAuth 2.0 | OpenID Connect (OIDC) |
|---|---|---|
| Purpose | Authorization (access delegation) | Authentication (identity verification) |
| Primary token | Access Token | ID Token (+ Access Token) |
| User info | Not included | Claims in ID token or /userinfo |
| Required scope | App-specific | openid (+ profile, email) |
| Answers "Who is this?" | No | Yes |
| Answers "Can they access X?" | Yes | Yes (also built on OAuth 2.0) |
| Spec | RFC 6749 | OpenID Foundation spec |
If you only remember one thing: when OAuth breaks in production, it's almost always the redirect URI, the state check, or where the tokens are stored. Check those three first.