Lesson 202 of 296
OAuth 2.0, OpenID Connect and PKCE
What you will learn
- The problem OAuth solves
- Roles in OAuth
- The Authorization Code flow, step by step
- PKCE and why it is required
- OpenID Connect and ID tokens
- Scopes, and which flows to avoid
On this page
The problem
A printing website wants to access your Google Photos. In the bad old days, it would ask for your Google password: it could then do anything with your account, forever. OAuth 2.0 solves this: you approve limited access on Google's own page, and the app receives a token with only that permission, which you can revoke. The app never sees your password.
"Log in with Google / Microsoft / Apple" works on top of OAuth with OpenID Connect.
Roles
| Role | Example |
|---|---|
| Resource owner | You, the user |
| Client | The app that wants access (the printing site, or your own front end) |
| Authorization server | Issues tokens after you log in and consent (Google's accounts service, Auth0, Microsoft Entra ID, Keycloak, Cognito) |
| Resource server | The API holding your data (Google Photos API) |
The Authorization Code flow with PKCE
This is the flow to know. It is the recommended flow for web apps, single-page apps and mobile apps.
Step 0 (client prepares PKCE): the client creates a random secret called the code verifier, and its SHA-256 hash, the code challenge.
Step 1 (redirect to log in): the client sends the user's browser to the authorization server:
https://accounts.example.com/authorize
?response_type=code
&client_id=jobprep-web
&redirect_uri=https://jobprep.example/auth/callback
&scope=openid profile email
&state=Xy7...random
&code_challenge=E9Melhoa2Owv...
&code_challenge_method=S256Step 2: the user logs in on the authorization server's page and approves the requested scopes.
Step 3 (redirect back with a code): the authorization server redirects to the client's registered redirect_uri with a short-lived authorization code and the same state:
https://jobprep.example/auth/callback?code=SplxlOBeZQ...&state=Xy7...randomStep 4 (exchange the code): the client checks state matches, then calls the token endpoint directly (not through the browser), sending the code and the code verifier:
POST https://accounts.example.com/token
grant_type=authorization_code&code=SplxlOBeZQ...&redirect_uri=...&client_id=jobprep-web&code_verifier=dBjftJeZ4CVP...Step 5: the server hashes the verifier, checks it equals the challenge from step 1, and returns tokens: an access token, often a refresh token, and with OpenID Connect an ID token.
Step 6: the client calls the resource server with Authorization: Bearer <access token>.
Why the steps exist
| Part | Protects against |
|---|---|
| Code instead of token in the URL | Tokens leaking through browser history, logs and Referer headers. The code is useless alone and short-lived |
| state | CSRF: an attacker tricking your browser into finishing a login with the attacker's code (logging you into the attacker's account) |
| PKCE (Proof Key for Code Exchange) | Code interception: if an attacker steals the code (a malicious app on the phone, a leaked log), they cannot exchange it without the verifier, which never left the client |
| Exact redirect URI matching | Codes being sent to an attacker's site |
| Client secret (confidential clients only) | Impersonating the app. Server-side apps can keep a secret; SPAs and mobile apps cannot, which is why they rely on PKCE |
Generating PKCE values:
import { randomBytes, createHash } from "node:crypto";
export function createPkcePair(): { verifier: string; challenge: string } {
const verifier = randomBytes(32).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");
return { verifier, challenge };
}OAuth 2.1 (the consolidated update of the standard) makes PKCE required for all clients using the authorization code flow.
Flows to avoid or use for special cases
| Flow | Status |
|---|---|
| Implicit flow (token returned directly in the URL) | Deprecated: tokens leak; use code + PKCE |
| Resource Owner Password Credentials (the app collects the user's password) | Deprecated: defeats the purpose of OAuth |
| Client Credentials | Correct for machine-to-machine calls with no user (a back-end job calling another service) |
| Device Authorization | For TVs and command-line tools ("go to example.com/device and enter code ABCD") |
OpenID Connect (OIDC)
OAuth is about authorisation: "this token can read photos". It does not say who the user is. OpenID Connect adds an identity layer:
- Request the
openidscope (plusprofile,email). - Receive an ID token: a JWT (Lesson 200) with claims about the user:
sub(a stable unique user ID at that provider),email,name,iss,aud(your client ID),exp, andnonce(replay protection). - The client validates the ID token: signature (using the provider's public keys from its JWKS endpoint), issuer, audience, expiry and nonce.
| Token | For | Read by |
|---|---|---|
| ID token | Telling the client who logged in | The client app only |
| Access token | Calling an API | The resource server |
Common mistake: sending the ID token to your API as if it were an access token, or using the access token to identify the user in the client.
Link accounts by the provider's sub plus the issuer, not by email alone (emails can change, and some providers do not verify them).
In practice
Use a proven library or service (Auth.js, Auth0, Clerk, Cognito, Keycloak, Microsoft Entra ID) rather than implementing the protocol yourself, but understand the flow so you can configure it securely and debug it. In a web app with a back end, the back end usually performs the code exchange and then creates its own session cookie (Lesson 200), so tokens never reach browser JavaScript. This is called the Backend-for-Frontend (BFF) pattern.
How to say it in an interview
"OAuth 2.0 lets a user grant an app limited access to an API without sharing their password, using an authorization server that issues tokens. The recommended flow is Authorization Code with PKCE: the client sends the user to the authorization server with a state value and a code challenge, gets a short-lived code back on an exactly matched redirect URI, and exchanges it on a back channel with the code verifier. state prevents CSRF and PKCE stops a stolen code being used; implicit and password flows are deprecated, and client credentials is for machine-to-machine. OpenID Connect adds an ID token, a JWT the client validates to know who logged in, while access tokens are for APIs. I prefer a backend-for-frontend that keeps tokens server-side behind a session cookie."
Key words
| Word | Meaning |
|---|---|
| OAuth 2.0 | A standard for delegated, limited access |
| Authorization server | Issues tokens after login and consent |
| Authorization code | A short-lived code exchanged for tokens |
| PKCE | Code verifier and challenge that stop stolen codes being used |
| state | A random value that protects the flow against CSRF |
| Scope | A named permission requested by the client |
| OpenID Connect | An identity layer on OAuth that adds ID tokens |
| ID token | A JWT telling the client who the user is |
| JWKS | The provider's published public keys for verifying tokens |
| BFF | Backend-for-Frontend: the server holds tokens, the browser gets a session cookie |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.