Whenever a user clicks "Sign in with Google" or connects their GitHub account to a CI platform without typing their password into a third-party website, OAuth 2.0 is doing the heavy lifting behind the scenes. Yet OAuth 2.0 is one of the most frequently misimplemented protocols in web development—largely because developers confuse authorization with authentication, copy outdated Implicit Flow blog posts, or embed secret keys directly inside frontend React bundles.
Modern security best practices (OAuth 2.1 / RFC 9700) standardize on one clean flow for single-page apps, mobile apps, and backend servers alike: Authorization Code Flow with PKCE (Proof Key for Code Exchange, pronounced "pixy"). In this guide, we walk through every actor in OAuth 2.0, explain why PKCE eliminates code-interception attacks, show working Web Crypto JavaScript code for generating code_verifier and code_challenge, and clarify how OpenID Connect (OIDC) connects OAuth with JWT tokens.
- 1. The Four OAuth 2.0 Roles & OAuth vs. OpenID Connect
- 2. Why Implicit Flow Died & Why Public Clients Cannot Keep Secrets
- 3. Authorization Code + PKCE: Step-by-Step Sequence
- 4. Generating
code_verifier&code_challengein JavaScript - 5.
statevs.nonce: Stopping Login CSRF & Replay Attacks - 6. Strict
redirect_uriMatching & URL Encoding Bugs - 7. Server-to-Server APIs: Client Credentials Flow
- 8. Troubleshooting Common OAuth Error Codes
1. The Four OAuth 2.0 Roles & OAuth vs. OpenID Connect
OAuth 2.0 defines four distinct participants:
- Resource Owner: The human user granting access to their data (for instance, their calendar or email profile).
- Client: Your application (a React SPA, Flutter mobile app, or Node.js web backend) requesting access.
- Authorization Server: The identity provider (Google, Auth0, Keycloak, Cognito) that authenticates the user and issues tokens.
- Resource Server: The API holding protected user resources that validates incoming Bearer access tokens.
OAuth 2.0 vs. OpenID Connect (OIDC): Strictly speaking, OAuth 2.0 is an authorization framework—it issues an opaque or JWT Access Token saying "this app can read Drive files", without defining a standard user identity format. OpenID Connect (OIDC) adds a thin identity layer on top of OAuth 2.0 (triggered by adding scope=openid profile email) that returns a standardized signed ID Token (JWT) containing claims like sub, name, and email. You can inspect decoded OIDC ID Tokens locally using our JWT Decoder.
2. Why Implicit Flow Died & Why Public Clients Cannot Keep Secrets
Traditional server-rendered web apps ("Confidential Clients") store a secret client_secret safely on the backend server and exchange an authorization code for tokens over a private server-to-server POST request. Single-page React/Vue apps and native iOS/Android apps ("Public Clients"), however, ship all code to the user's device—meaning anyone can decompile the mobile binary or inspect browser DevTools to steal a hardcoded client_secret.
Years ago, OAuth recommended the Implicit Flow (response_type=token) for SPAs, returning the raw access token directly in the browser URL fragment (#access_token=...). That turned out to be dangerous: tokens leaked via browser history, server logs, open-redirect bugs, and malicious browser extensions, and refresh tokens couldn't be issued safely. Today, OAuth 2.1 officially deprecates Implicit Flow in favor of Authorization Code + PKCE.
3. Authorization Code + PKCE: Step-by-Step Sequence
PKCE (RFC 7636) solves the missing client_secret problem by creating a fresh, one-time cryptographic secret for every single login attempt:
- Client generates a random
code_verifier: A cryptographically random string (43–128 characters) kept strictly in memory/sessionStorage on the client. - Client hashes it into
code_challenge: ComputesBase64URL(SHA256(code_verifier)). - Browser redirects to
/authorize: Sendsclient_id,redirect_uri,response_type=code,scope,state,code_challenge, andcode_challenge_method=S256. Notice the authorization server stores the hashed challenge. - User logs in & approves consent: Authorization server redirects back to
redirect_uri?code=AUTH_CODE&state=XYZ. - Client exchanges
code+ originalcode_verifier: Sends a POST request to/tokencontaining thecodeand the raw unhashedcode_verifier. - Authorization server verifies the hash: Computes
Base64URL(SHA256(code_verifier))and checks that it matches the storedcode_challengebefore issuing Access, Refresh, and ID tokens!
Why does this stop interception attacks? Even if a rogue app on Android intercepts the redirect containing ?code=AUTH_CODE, it cannot exchange that code at /token because it never possessed the original code_verifier created inside your app's memory!
4. Generating code_verifier & code_challenge in JavaScript
Using the browser's built-in crypto.subtle Web Crypto API, generating a spec-compliant S256 PKCE pair requires zero external dependencies:
function toBase64Url(uint8Array) {
let bin = "";
for (const byte of uint8Array) bin += String.fromCharCode(byte);
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
export async function createPkcePair() {
const randomBytes = new Uint8Array(32);
crypto.getRandomValues(randomBytes);
const codeVerifier = toBase64Url(randomBytes); // 43 URL-safe characters
const encoded = new TextEncoder().encode(codeVerifier);
const digest = await crypto.subtle.digest("SHA-256", encoded);
const codeChallenge = toBase64Url(new Uint8Array(digest));
return { codeVerifier, codeChallenge };
}
Notice how PKCE uses Base64URL (- and _ without = padding) so the verifier and challenge travel cleanly inside query parameters without corrupting URL syntax—learn more in our Base64 Encoding Guide or test strings inside our Base64 Tool.
5. state vs. nonce: Stopping Login CSRF & Replay Attacks
| Parameter | Protects Against | How It Works |
|---|---|---|
state | Login CSRF Attacks | Random string generated before redirect, verified when /callback?state=... returns. Prevents attackers from tricking a victim into binding the attacker's account. |
nonce (OIDC) | ID Token Replay Attacks | Random string sent to /authorize and echoed verbatim inside the signed ID Token's nonce claim. |
Never skip validating state on your callback handler! Compare the returned state query parameter strictly against the value stored before redirecting out.
6. Strict redirect_uri Matching & URL Encoding Bugs
Two of the most frequent OAuth setup errors come straight from redirect_uri mismatches:
- Exact string comparison: Identity providers match
redirect_uricharacter for character—https://techcar.online/callbackandhttps://techcar.online/callback/(with trailing slash) are treated as different URLs! - Unencoded query parameters: Always build your authorization URL using
URLandURLSearchParamssoredirect_uriandscopeencode cleanly (debug tricky authorization URLs instantly inside our URL Encoder & Query Parser). - Never allow wildcard redirect URIs: Allowing
https://*.techcar.online/*lets an open-redirect bug on any subdomain steal authorization codes.
7. Server-to-Server APIs: Client Credentials Flow
When a backend cron job or microservice calls another internal API with no human user involved, do not simulate browser logins. Use the Client Credentials Grant (grant_type=client_credentials), where the server authenticates directly against /token using its client_id and client_secret over HTTPS to obtain a machine access token, caching that token until shortly before exp.
// Server-to-Server Client Credentials token request
const body = new URLSearchParams({
grant_type: "client_credentials",
client_id: process.env.OAUTH_CLIENT_ID,
client_secret: process.env.OAUTH_CLIENT_SECRET,
scope: "invoices:read orders:write"
});
const res = await fetch("https://auth.techcar.online/oauth/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body
});
8. The Backend-for-Frontend (BFF) Pattern & Refresh Race Conditions
For high-security SaaS dashboards, many architects move OAuth token handling out of browser JavaScript entirely using a lightweight Backend-for-Frontend (BFF) proxy on the same origin (for example, https://techcar.online/auth/*). In a BFF setup, the BFF performs the Authorization Code + PKCE exchange on the server, keeps the raw Access and Refresh tokens inside an encrypted server-side Redis session, and issues only an HttpOnly; Secure; SameSite=Lax cookie to the browser—completely shielding OAuth tokens from XSS.
Additionally, if your app uses Refresh Token Rotation in parallel browser requests (three widgets firing simultaneously right when a 5-minute access token expires), deduplicate the refresh call using a single shared in-flight Promise lock! Without a lock, Request 1 rotates the refresh token, Request 2 replays the now-revoked old refresh token milliseconds later, and the auth server assumes token theft and logs the user out abruptly.
9. Principle of Least Privilege: Designing OAuth Scopes & Token Lifetimes
One of the most common mistakes in OAuth 2.0 integrations is requesting overly broad scopes on day one—for example, asking for full read/write repository or mailbox access when your feature only needs a user's display name and email address. Modern identity providers enforce incremental consent reviews and highlight broad permission prompts aggressively to users, reducing login conversion rates and increasing blast radius if a token ever leaks. Always request the narrowest possible scope set (openid email profile for authentication, adding granular API scopes only at the moment a user enables a specific integration).
Pair minimal scopes with disciplined token lifetimes: keep short-lived access tokens between five and fifteen minutes, restrict refresh token validity to sensible idle windows, and implement clean logout revocation hooks that clear both server-side refresh families and client-side state. Whenever you debug a failing OIDC login callback, check three items in sequence: inspect the exact query parameters returned to your callback inside our URL Query Parser, decode the returned ID or Access JWT locally inside our JWT Decoder to verify aud, iss, and exp, and confirm your cross-origin token exchange allows POST requests cleanly under your CORS policy.
8. Troubleshooting Common OAuth Error Codes
| Error Response | Typical Root Cause |
|---|---|
invalid_grant | Authorization code already used once, expired (codes usually live 30–60 seconds), code_verifier didn't match code_challenge, or redirect_uri in /token differed from /authorize. |
redirect_uri_mismatch | Callback URL trailing slash, scheme (http vs https), or port differs from provider dashboard allowlist. |
invalid_client | Wrong client_id/client_secret, or sending a client_secret from a public client configured without secret auth. |
access_denied | User clicked "Cancel" on consent screen or lacks required organization workspace permissions. |
Frequently Asked Questions
Should backend web apps with a client_secret still use PKCE?
Yes! OAuth 2.1 recommends using PKCE for all clients (both public and confidential), because combining client_secret with PKCE adds defense-in-depth against authorization code injection.
Can I use plain instead of S256 for code_challenge_method?
Avoid plain in production. Always use S256 (SHA-256) so network observers or device logs seeing the initial /authorize URL never learn the raw code_verifier.
What is the difference between an Access Token and an ID Token?
An ID Token is strictly for your client app to verify who signed in (always a JWT). An Access Token is sent in Authorization: Bearer ... headers to call backend APIs (may be a JWT or an opaque string).
Where should SPAs store OAuth tokens after login?
Ideally keep tokens behind a lightweight Backend-for-Frontend (BFF) using HttpOnly; Secure; SameSite cookies, or keep short-lived access tokens strictly in JavaScript memory rather than localStorage. Read our Browser Storage Security Guide for full details.