Explain it simply
OAuth 2.0 in plain language
OAuth 2.0 is a way for an app to use your data on another service, in a limited way, without ever knowing your password. A hotel key card is a good comparison. You prove who you are at the front desk (the provider), and the desk hands the app a key card that opens only some doors and stops working after a while. The app never sees your own credentials.
The key idea is that login and approval happen on the provider's own page. The app sends the user there, gets a code when the user comes back, trades that code for a token, and then calls the API. In short, OAuth answers 'what may this app do', more than 'who is this person'.
Problem → Why → Solution
The problem: an app that asks for another service's password
Suppose a 'print my photos' app asks you for your photo service email and password. The app can call the photo API with them, but it now holds your entire account. You cannot limit it to reading photos, and the only way to cut it off is to change your password. If the app's database leaks, so does your password, along with every other site where you reused it.
// BROKEN design: the app asks the user for their password to ANOTHER service
const { email, password } = await promptUser("Enter your PhotoShare login");
const res = await fetch("https://api.example.com/photos", {
headers: { Authorization: "Basic " + btoa(`${email}:${password}`) },
});
// The app now holds a credential that can do everything, forever.A scoped token instead of a password
A password grants everything, never expires and cannot be narrowed. OAuth gives the app a substitute credential called a token instead. The token is limited by scopes such as 'read photos only', lives for a short time, and can be revoked by the user or the provider. And it is issued by the service that actually knows the user.
Core concept: the authorization code flow with PKCE
OAuth has four roles: the resource owner (the user), the client (the app that wants the data), the authorization server (the provider side that handles login and consent and issues tokens) and the resource server (the API that accepts tokens). The most common approach is the authorization code flow: the code comes back through a browser redirect, but the token is fetched in a direct request between the app and the provider.
Authorization code flow with PKCE
---------------------------------
App (with browser) Authorization server Resource API
| | |
1 |-- GET /authorize --------->| |
| client_id, redirect_uri, scope, state, code_challenge |
2 |<-- login + consent ------->| (the password is typed |
| | here, never in the app) |
3 |<-- 302 redirect_uri?code=...&state=... |
4 |-- POST /token ------------>| |
| code + code_verifier | |
5 |<-- access_token -----------| |
6 |-- GET /api/me, Authorization: Bearer <token> ----------->|Read the redirects like this. In the first redirect (step 1) the app sends the user's browser to the provider's /authorize URL. The user logs in there and clicks 'Allow'. In the second redirect (step 3) the provider sends the browser back to the app's redirect_uri carrying a code and the state. Only then does the app send the code to the provider's /token endpoint itself and receive an access token. The code passes through the browser and anything near it, so it must be single-use and short-lived.
| Parameter | What it is for |
|---|---|
| client_id | The public identifier of the app, registered with the provider |
| redirect_uri | Where the code is sent back; it must match a registered URL exactly |
| scope | The permissions the app asks for, such as read:profile |
| state | A random value the app invents; checking it on return proves the response belongs to its own login and blocks CSRF |
| code_challenge | The SHA-256 hash of code_verifier (method S256), sent in step 1 |
| code | The single-use authorization code that comes back in the redirect |
| code_verifier | The original random secret, revealed only in step 4 so the provider can re-hash and compare |
A client secret is how an app that runs on a server (a confidential client) proves itself at the token endpoint. Browser JavaScript and mobile apps (public clients) cannot keep a secret, because anyone can extract it. PKCE takes its place: the app invents a verifier and sends only its hash first, so someone who steals the code cannot exchange it without the verifier.
- App sends the user to the provider
- User logs in there and approves
- Provider redirects back with a code
- App swaps code + verifier for a token
- App calls the API with Bearer <token>
The password stays with the provider, and the app holds only a token that is limited in scope and short in life.
General pattern
1. GET <authorize-url>?response_type=code&client_id=...&redirect_uri=...
&scope=...&state=...&code_challenge=...&code_challenge_method=S256
2. 302 <redirect_uri>?code=...&state=...
3. POST <token-url>
grant_type=authorization_code&code=...&redirect_uri=...
&client_id=...&code_verifier=...
4. 200 { "access_token": "...", "token_type": "Bearer", "expires_in": 900 }The provider supplies two URLs, authorize and token. Every parameter travels in a query string (steps 1 and 2) or a form body (step 3).
Worked example: run the whole flow against a mock provider
The script below imitates a provider inside a single process, with /authorize, /token and /api/me. The client follows the steps of the diagram: it creates a verifier and a state, calls /authorize, reads the redirect and checks the state, trades the code for a token, and only then calls the API. Along the way it also tries a wrong redirect_uri, a wrong verifier and a replayed code, and shows how the provider rejects each.
A browser follows redirects on its own, so the script uses redirect: 'manual' to stop at the 302 and read the Location header. The codes come from a counter so the output repeats (real codes are random), while the verifier and state are random and are never printed. Nothing ever contacts https://app.example.com/callback.
import http from "node:http";
import crypto from "node:crypto";
const s256 = (text) => crypto.createHash("sha256").update(text).digest("base64url");
const REDIRECT_URI = "https://app.example.com/callback"; // registered with the provider
// A mock provider: authorization endpoint, token endpoint and API in one process.
const pendingCodes = new Map(); // code -> what the provider remembers about the request
let codeCounter = 0;
const provider = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://provider.local");
const json = (status, body) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (url.pathname === "/authorize") {
const q = url.searchParams;
// Never redirect to an unregistered redirect_uri: the code would go to a stranger.
if (q.get("client_id") !== "demo-app" || q.get("redirect_uri") !== REDIRECT_URI) {
return json(400, { error: "invalid_request" });
}
// A real provider shows its login and consent screen here; we pretend "Allow".
const code = `code_${++codeCounter}`;
pendingCodes.set(code, { challenge: q.get("code_challenge"), scope: q.get("scope") });
const back = new URL(REDIRECT_URI);
back.searchParams.set("code", code);
back.searchParams.set("state", q.get("state"));
res.writeHead(302, { Location: back.href });
return res.end();
}
if (url.pathname === "/token" && req.method === "POST") {
let raw = "";
for await (const chunk of req) raw += chunk;
const form = new URLSearchParams(raw);
const pending = pendingCodes.get(form.get("code"));
if (!pending || s256(form.get("code_verifier") ?? "") !== pending.challenge) {
return json(400, { error: "invalid_grant" });
}
pendingCodes.delete(form.get("code")); // a code works exactly once
const grant = { access_token: "at_demo_1", token_type: "Bearer", expires_in: 900 };
return json(200, { ...grant, scope: pending.scope });
}
if (url.pathname === "/api/me" && req.headers.authorization === "Bearer at_demo_1") {
return json(200, { name: "Alice" });
}
json(401, { error: "invalid_token" });
});
await new Promise((resolve) => provider.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${provider.address().port}`;
// Step 1: the client invents a one-time secret (the verifier) and sends only its hash.
const codeVerifier = crypto.randomBytes(32).toString("base64url");
const state = crypto.randomBytes(16).toString("base64url");
const authorizeParams = {
response_type: "code",
client_id: "demo-app",
redirect_uri: REDIRECT_URI,
scope: "read:profile",
state,
code_challenge: s256(codeVerifier),
code_challenge_method: "S256",
};
const authorizeUrl = (overrides = {}) =>
`${base}/authorize?${new URLSearchParams({ ...authorizeParams, ...overrides })}`;
const bad = await fetch(authorizeUrl({ redirect_uri: "https://evil.example/cb" }));
console.log("bad redirect_uri :", bad.status, (await bad.json()).error);
// Step 2: a browser would follow this URL; we stop at the 302 to read its Location.
const hop = await fetch(authorizeUrl(), { redirect: "manual" });
const callback = new URL(hop.headers.get("location"));
console.log("redirected to :", callback.origin + callback.pathname);
console.log("state matches :", callback.searchParams.get("state") === state);
const code = callback.searchParams.get("code");
// Step 3: swap the code (plus the original verifier) for an access token.
async function exchange(verifier) {
const res = await fetch(`${base}/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: REDIRECT_URI,
client_id: "demo-app",
code_verifier: verifier,
}),
});
return { status: res.status, body: await res.json() };
}
const thief = await exchange("a-guess-by-someone-who-stole-the-code");
console.log("wrong verifier :", thief.status, thief.body.error);
const granted = await exchange(codeVerifier);
const { token_type, expires_in, scope } = granted.body;
console.log("token response :", granted.status, token_type, expires_in, scope);
const replay = await exchange(codeVerifier);
console.log("code replay :", replay.status, replay.body.error);
const auth = { Authorization: `Bearer ${granted.body.access_token}` };
const me = await fetch(`${base}/api/me`, { headers: auth });
console.log("API with token :", me.status, await me.text());
provider.close();Code breakdown
- Registered redirect_uri
if (q.get("client_id") !== "demo-app" || q.get("redirect_uri") !== REDIRECT_URI) {The provider compares redirect_uri with the registered value exactly. On a mismatch it answers 400 and sends no code, because otherwise the code would land on an attacker's URL.
- PKCE pair
code_challenge: s256(codeVerifier),The client keeps the random verifier to itself and sends only its hash, the challenge, in step 1. A hash cannot be turned back into the verifier, so anyone who sees the redirect still lacks it.
- Stop at the redirect
const hop = await fetch(authorizeUrl(), { redirect: "manual" });With redirect: 'manual' fetch does not follow the 302 and hands back the Location header. In a real browser this is where the user would see the provider's login page.
- Check state
console.log("state matches :", callback.searchParams.get("state") === state);The returned state must equal the one that was sent. If it does not, this response does not belong to the login this app started, and the code must be ignored.
- Provider verifies PKCE
if (!pending || s256(form.get("code_verifier") ?? "") !== pending.challenge) {The token endpoint hashes the verifier it received and compares it with the challenge stored in step 1. A thief who has the code but not the verifier gets invalid_grant.
- Single-use code
pendingCodes.delete(form.get("code")); // a code works exactly onceAfter a successful exchange the code is deleted at once, which is why the replay at the end fails with invalid_grant.
bad redirect_uri : 400 invalid_request
redirected to : https://app.example.com/callback
state matches : true
wrong verifier : 400 invalid_grant
token response : 200 Bearer 900 read:profile
code replay : 400 invalid_grant
API with token : 200 {"name":"Alice"}What actually goes over the wire
The authorize URL sent to the browser is a single line; it is wrapped here for reading. Parameter values must be percent-encoded, which is why the : and / in redirect_uri appear as %3A and %2F. The challenge value is the sample from RFC 7636.
https://auth.example.com/authorize
?response_type=code
&client_id=demo-app
&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
&scope=read%3Aprofile
&state=af0ifjsldkj
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256After the user approves, the provider answers with a redirect like the one below. Then the app's backend (or SPA) sends the token request itself. That request never appears in the browser's address bar, which is why the token comes back in the response body instead of a URL.
HTTP/1.1 302 Found
Location: https://app.example.com/callback?code=7xK2qLw9&state=af0ifjsldkjPOST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=7xK2qLw9&client_id=demo-app
&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXkThe last request body is really one line, and it is wrapped here for reading. The provider answers 200 with JSON containing access_token, token_type: Bearer and expires_in.
PKCE: how it protects the code
Without PKCE, anyone who intercepts the redirect can trade the code for a token: a malicious app registered for the same custom URL scheme on a phone, a browser extension, a log. PKCE binds the code to the app instance that started the flow: the challenge goes out in step 1 and the verifier is revealed only in step 4.
import crypto from "node:crypto";
// The example pair published in RFC 7636 (PKCE), Appendix B.
const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
console.log(challenge);
console.log(challenge === "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
// A fresh verifier is 32 random bytes written as 43 base64url characters.
console.log(crypto.randomBytes(32).toString("base64url").length);The first line is the sample verifier from RFC 7636 hashed with SHA-256 and written in base64url, the second confirms it equals the value printed in the RFC, and the last shows that a fresh verifier is 32 random bytes written as 43 characters.
Client credentials: when there is no user
When a nightly job or one backend calls another, there is no user, so there is no redirect and no code. The client proves itself directly at /token with its client_id and client_secret, usually in an HTTP Basic header. The token carries the service's own scopes, and no refresh token is usually issued; when the token expires, the client just asks again. This flow belongs on a server only, because it involves a secret.
import http from "node:http";
// Client credentials: no user, no redirect. The server proves itself with id + secret.
const tokenEndpoint = http.createServer(async (req, res) => {
let raw = "";
for await (const chunk of req) raw += chunk;
const form = new URLSearchParams(raw);
const basic = (req.headers.authorization ?? "").replace(/^Basic /, "");
const [id, secret] = Buffer.from(basic, "base64").toString().split(":");
const reply = (status, body, headers = {}) => {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(body));
};
if (form.get("grant_type") !== "client_credentials") {
return reply(400, { error: "unsupported_grant_type" });
}
if (id !== "billing-service" || secret !== "demo-secret-not-real") {
const challenge = { "WWW-Authenticate": 'Basic realm="oauth"' };
return reply(401, { error: "invalid_client" }, challenge);
}
reply(200, { access_token: "at_service_1", token_type: "Bearer", expires_in: 3600 });
});
await new Promise((resolve) => tokenEndpoint.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${tokenEndpoint.address().port}/token`;
async function requestToken(id, secret) {
const credentials = Buffer.from(`${id}:${secret}`).toString("base64");
const res = await fetch(url, {
method: "POST",
headers: {
Authorization: `Basic ${credentials}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({ grant_type: "client_credentials", scope: "invoices" }),
});
console.log(res.status, await res.text());
}
await requestToken("billing-service", "demo-secret-not-real");
await requestToken("billing-service", "wrong-secret");
tokenEndpoint.close();The first call returns 200 with a token, and the second fails with 401 and invalid_client because the secret is wrong. When client authentication fails over the Authorization header, the OAuth spec says the provider answers 401 with a Basic challenge.
Scopes, access tokens and refresh tokens
Scopes are words defined by the provider, such as read:profile, requested as a space-separated list. On the consent screen the user sees what the app asks for and decides whether to allow it. Ask for no more than you need: more scopes mean more users saying no, and more damage if the token leaks.
| Token | Lifetime | Sent to |
|---|---|---|
| Access token | Minutes to a few hours | The resource API (Authorization: Bearer) |
| Refresh token | Days to months | Only the provider's token endpoint |
When the access token expires, the app sends the refresh token to the token endpoint with grant_type=refresh_token and receives a new access token, without asking the user to log in again. A refresh token is more valuable, so store it somewhere better protected and never send it to the API.
In real projects
OAuth in real projects
The 'Sign in with Google' or 'Sign in with GitHub' buttons are OAuth with an identity layer called OpenID Connect on top. A calendar app reading your Google Calendar, a chat bot posting into a workspace, and a CI service looking at a repository are all authorised through OAuth. As a developer you register the app in the provider's developer console, receive a client_id, and list the exact redirect URIs.
- Each provider's endpoint URLs, available scopes and redirect rules are in its documentation; this lesson teaches the shape they all share.
- Mobile apps open the system browser and run the flow with PKCE; they do not use a login form embedded inside the app.
- Server-to-server integrations such as billing or reporting jobs get a token with client credentials and cache it until it expires.
- Use an OAuth library. Token refresh, error handling and provider quirks are easy to get wrong when written by hand.
Common mistakes
Common mistakes with OAuth
Putting a client secret in a browser or mobile app
Anyone can extract a secret from an app package, and obfuscating or base64-encoding it only lengthens the route. Public clients use the authorization code flow with PKCE and no secret.
Skipping the state check
Without the state check, an attacker can send a callback link carrying a code from their own account and tie the victim's session to the attacker's account (login CSRF). Generate a random state at the start of each flow, keep it in the session, and compare it in the callback.
Treating OAuth as login
An access token lets you call an API; it does not say which user you are talking to. For sign-in, use the OpenID Connect id_token and verify its signature, iss, aud and nonce.
Using outdated flows
The implicit flow sends tokens in a URL fragment and the password grant hands the user's password back to the app, so current OAuth security guidance advises against both. For anything new, choose authorization code with PKCE.
Best practices
Best practices
- Use PKCE for every public client, and it is a useful extra defence for server-side apps too.
- Register redirect URIs exactly and avoid wildcards.
- Request only the scopes you need and keep access tokens short-lived.
- Never write tokens or codes to logs, and prefer a maintained OAuth library.
Mini challenge
Mini challenge: a client-credentials token cache
A service-to-service client should not request a fresh token for every API call. Write a mock token endpoint (each call issues at_1, at_2 and so on with expires_in 60), then write getToken(): it returns the cached token while more than 5 seconds of life remain, and otherwise requests a new one with client_credentials. Test it with a fake clock.
- The mock endpoint counts what it issued and returns an at_<n> token
- getToken sends grant_type=client_credentials in the form body
- Keep using the cache while the token has more than 5 seconds of life left
- Advance the clock by 54 seconds, then by 1 more, and print the token and the issued count each time
import http from "node:http";
// TODO: a mock token endpoint on port 0 that counts the tokens it has issued
// and answers { access_token: "at_<n>", token_type: "Bearer", expires_in: 60 }
// TODO: a fake clock in seconds (let clock = 1000) so the output repeats
// TODO: getToken() -> the cached token while it stays valid for more than 5 more
// seconds, otherwise POST grant_type=client_credentials and cache the new token
// TODO: call getToken() twice, advance the clock 54 s and call again, advance
// 1 s more and call again; print each token and the issued countExpected: The first two calls print at_1 at_1 (issued: 1), 54 seconds later prints at_1 (issued: 1), and at 55 seconds it prints at_2 (issued: 2).
Show hint
Store the token value and expiresAt (the current clock plus expires_in) in the cache. Reuse it only when expiresAt - 5 > clock, and remember that the cache is null on the very first call.
Show solution
import http from "node:http";
let issued = 0;
const tokenServer = http.createServer(async (req, res) => {
for await (const chunk of req) void chunk; // drain the request body
issued += 1;
res.writeHead(200, { "Content-Type": "application/json" });
const grant = { access_token: `at_${issued}`, token_type: "Bearer", expires_in: 60 };
res.end(JSON.stringify(grant));
});
await new Promise((resolve) => tokenServer.listen(0, "127.0.0.1", resolve));
const tokenUrl = `http://127.0.0.1:${tokenServer.address().port}/token`;
let clock = 1000; // fake "now" in seconds, so the output repeats
let cached = null;
async function getToken() {
if (cached && cached.expiresAt - 5 > clock) return cached.value; // 5 s safety margin
const res = await fetch(tokenUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "client_credentials" }),
});
const data = await res.json();
cached = { value: data.access_token, expiresAt: clock + data.expires_in };
return cached.value;
}
const first = await getToken();
const second = await getToken();
console.log("first two calls :", first, second, `(issued: ${issued})`);
clock += 54;
console.log("54 s later :", await getToken(), `(issued: ${issued})`);
clock += 1;
console.log("55 s later :", await getToken(), `(issued: ${issued})`);
tokenServer.close();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- OAuth 2.0 gives an app a scoped, short-lived token instead of a password, and keeps login on the provider's own page.
- Authorization code flow: redirect to /authorize, redirect back with code and state, swap code + code_verifier at /token, call the API with the Bearer token.
- PKCE and state defend against a stolen code and against CSRF, and a browser or mobile app never holds a client secret.
- Client credentials is for server-to-server calls with no user, and its token should be cached until it expires.