15 min read
OAuth vs OpenID Connect: how Google login works
In one sentence: OAuth 2.0 gives a website limited permission on another service without it seeing your password, and OpenID Connect adds who you are. “Sign in with Google” is exactly that: Google checks your password, and the shop gets a signed token that says who you are.
What you will learn
- Explain why a website shouldn't ask you for another site's password, and what role each party plays in OAuth.
- Follow the authorization code flow with PKCE, and say what the state, the nonce and the verifier stop.
- Tell OAuth's permission (access_token) apart from OpenID Connect's identity (id_token).
- Link accounts by the provider's identifier, and by email only if it's verified.
Before you start, read: 03-jwt.md
The problem
Section titled “The problem”Imagine a photo printing website that asks for your Google password to fetch your photos. With it, it can read your email, delete your files or change the password. And forever: the only way to take that away is to change your password. If the website suffers a data breach, your Google account goes with it.
The shop has the opposite problem. Marta doesn’t want yet another password, and she wants to press “Sign in with Google.” How does Google tell the shop who Marta is, without Marta giving it her password?
Two standards solve it: OAuth 2.0 gives permissions, and OpenID Connect says who you are. You’ll try them against a provider that plays Google on your computer.
The analogy
Section titled “The analogy”The analogy
You miss work because you’re sick. Your company doesn’t examine you: the doctor gives you a stamped sick note, with your name and the date, and your company recognizes the health center’s stamp.
“Sign in with Google” is that. The shop doesn’t check Marta’s password: Google checks it, and gives the shop a signed note.
Where the analogy breaks down
- You carry the sick note yourself, and you could change it. Here, the browser only carries a single-use pickup number, and the shop collects the note from the provider itself, with its own secret.
- A stamp can be copied; the provider’s signature can’t be made without its private key.
- A sick note doesn’t give permissions. OAuth does: to see your photos, and not your email.
How it really works
Section titled “How it really works”Four roles: who’s who
Section titled “Four roles: who’s who”OAuthA standard that lets an app get limited permission on your account with another service, like viewing your photos, without knowing your password. You give the permission on the service’s own website, and the service hands the app a key that opens only that and that you can take back whenever you want.Go to definition (RFC 6749, from 2012) hands out four roles. With the photo website and with the shop:
| Role | What it does | Photo website | In the shop |
|---|---|---|---|
| Resource owner | Gives the permission | You | Marta |
| Client | The application that asks for access | The photo website | The shop’s API |
| Authorization server | Checks who you are and gives out the tokens | Google, or the practice provider | |
| Resource server | The API with the data | Google Photos | None |
Careful with “client”: here it’s the shop, not the browser or a customer. And the authorization server that says who you are is called the identity provider, or just the provider.
OAuth gives permissions; OpenID Connect says who you are
Section titled “OAuth gives permissions; OpenID Connect says who you are”OAuth is for giving permissions. You go to Google’s website, and Google asks you: “Do you let this website see your photos?” If you say yes, it gives the website an access_token: a token to call the Google Photos API, with a specific permission (the scope) and an expiry. The website never sees your password.
But an access_token doesn’t say who you are: it’s a key for an API, not an ID card.
OpenID ConnectA layer on top of OAuth for signing in to a website with your account on another service, like “Sign in with Google.” That service checks who you are and gives the website a signed JWT that says who you are and which website it’s for.Go to definition (2014) adds who you are, on top of OAuth. If the website asks for the openid scope, the provider also gives it an id_token: a JWTJWT stands for JSON Web Token.A piece of text with some data in JSON, like who someone is and until when it’s valid, and a signature that proves who issued it and that nobody has changed it. It usually isn’t encrypted, so anyone who has it can read it, and it can’t be canceled before it expires without keeping a separate list.Go to definition, like the ones in lesson 3, signed with the provider’s Private keyThe half of a key pair that only its owner knows. It decrypts what was encrypted with its public key and signs messages anyone can check with the public key. If it leaks, it must be replaced.Go to definition. It carries who issues it (iss), which website it’s for (aud), until when it’s valid (exp) and, above all, sub: the person’s identifier at that provider, which never changes.
| access_token (OAuth) | id_token (OpenID Connect) | |
|---|---|---|
| Who it’s for | An API | The website that asked for the sign-in |
| What it says | What can be done | Who has signed in, and for which website |
| Who uses it | The website sends it to the API, without reading it | The website checks it and reads it |
The authorization code flow, step by step
Section titled “The authorization code flow, step by step”For a website, RFC 9700 (2025), OAuth’s security best practices, recommends the authorization code flow with PKCE.
- Shoprandom state, nonce and verifier,
kept in a cookie - Shop → Marta's browser302 to the provider
client_id, state, nonce and code_challenge - Marta's browser · ProviderMarta signs in at the provider
and agrees to share her email - Provider → Marta's browser302 to the shop
code and state - ShopIs the state the one in the cookie?
- Provider → Shopid_token and access_token
- Shopiss, aud, nonce and exp
- Shop → Marta's browser303 to /v2/me
Set-Cookie: session=…
- Marta presses the button, and her browser asks the shop for
/v2/session/provider. - The shop creates three random values, keeps them in a and answers with a RedirectAn HTTP response that says “what you’re looking for is at another address.” It carries a code starting with 3, such as 301, and the Location header with the new address. The browser requests it on its own, without you doing anything.Go to definition to the provider (lesson 3 of Phase 2).
- Marta signs in at the provider, with her password there, and agrees.
- The provider sends the browser back to the shop’s callback URL with a
code: a single-use code that expires in minutes. - The shop checks the state and exchanges the code for the tokens in a direct request to the provider, ServerA program that waits for requests and answers them. By extension, the computer it runs on is also called a server.Go to definition to server.
- It checks the id_token and opens a session, the one from lesson 2.
Why a code, and not the token directly? Whatever goes through the browser is in plain view: in the history, in the logs, in the extensions. The code alone is useless: exchanging it takes the shop’s secret and the verifier. RFC 9700 advises against the old “implicit” flow, with the token in the URL.
PKCE: the code is useless without the verifier
Section titled “PKCE: the code is useless without the verifier”PKCEPKCE stands for Proof Key for Code Exchange.A protection for signing in with OAuth. The website makes up a random secret and, at the start, only sends its hash; to exchange the code it receives on the way back, it has to show the secret, so a stolen code is useless to anyone else.Go to definition (“pixie”) protects the code in case someone steals it along the way:
- Before sending the browser to the provider, the shop makes up a verifier: 32 random bytes.
- On the way there it only sends its SHA-256 HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition, the
code_challenge. - When exchanging the code, it sends the verifier. The provider computes its hash and compares it with the challenge.
Whoever steals the code doesn’t have the verifier, and can’t get it from the challenge: a hash can’t be undone. PKCE was born for phone apps, which can’t keep a secret; RFC 9700 also recommends it to websites with a secret, like the shop.
The state and the nonce: the way back, tied to whoever started it
Section titled “The state and the nonce: the way back, tied to whoever started it”Without a state, someone could start a sign-in with their own account, stop before coming back and send Marta the callback link with their code. Marta opens it and is signed in as the attacker: whatever she saves, her address or her card, ends up in the attacker’s account. It’s a CSRFCSRF stands for Cross-Site Request Forgery.An attack in which a page makes your browser send a request to a site where you’re logged in, with your cookies, to do something on your behalf, such as changing your email or buying something. CORS doesn’t prevent it, because many requests reach the server even if the page can’t read the response.Go to definition on sign-in (lesson 7).
The state prevents it: a random value the shop keeps in Marta’s browser and the provider returns as is. If they don’t match, this browser didn’t start that way back. The nonce travels inside the id_token and ties it to this sign-in.
The shop creates them in src/provider.ts, with openid-client, by the author of jose:
export async function startSignIn(): Promise<{ url: URL; saved: SavedStart }> { const saved = { state: oidc.randomState(), nonce: oidc.randomNonce(), verifier: oidc.randomPKCECodeVerifier(), }; const url = oidc.buildAuthorizationUrl(await provider(), { redirect_uri: config.OIDC_REDIRECT_URI, // openid: we want to know who it is (OpenID Connect, not just OAuth); email and profile, their // data. scope: 'openid email profile', code_challenge: await oidc.calculatePKCECodeChallenge(saved.verifier), code_challenge_method: 'S256', state: saved.state, nonce: saved.nonce, }); return { url, saved };}randomState(),randomNonce()andrandomPKCECodeVerifier(): 32 random bytes each.buildAuthorizationUrlbuilds the URL to the provider. It read where/authorizeis in/.well-known/openid-configuration, a JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition document every provider publishes with its addresses.scope:openidturns OAuth into OpenID Connect.
The route that sends the browser to the provider, in src/v2.ts, keeps the three values in a cookie:
// What has to be remembered between the way out and the way back (state, nonce and verifier) goes// in a cookie of its own, instead of in a table: it lasts 10 minutes, only travels to the// provider's two routes (Path) and JavaScript doesn't read it (HttpOnly). Its job is to tie the way// back to the browser that started: another browser doesn't have it. SameSite=Lax and not Strict:// the way back comes from the provider's site, and with Strict the browser wouldn't send it.const PROVIDER_COOKIE = 'provider';const PROVIDER_ATTRIBUTES = { httpOnly: true, secure: true, sameSite: 'Lax', path: '/v2/session/provider',} as const;
v2.openapi(contract.startProviderSignIn, async (c) => { const { url, saved } = await startSignIn(); const value = Buffer.from(JSON.stringify(saved)).toString('base64url'); setCookie(c, PROVIDER_COOKIE, value, { ...PROVIDER_ATTRIBUTES, maxAge: 10 * 60 }); return c.redirect(url.href, 302);});path: it only travels to the provider’s two routes, for 10 minutes.sameSite: 'Lax', and notStrict: the way back comes from the provider’s website, and withStrictthe browser wouldn’t send the cookie (Phase 2’s cookies lesson).
The callback route reads the cookie and deletes it: each sign-in is finished only once. After that, step 5 is one function:
const tokens = await oidc.authorizationCodeGrant(await provider(), callback, { expectedState: saved.state, expectedNonce: saved.nonce, pkceCodeVerifier: saved.verifier, idTokenExpected: true,});authorizationCodeGrant checks the state, exchanges the code with the secret and the verifier, and checks the id_token: iss, aud, the nonce and exp. If something fails, the route answers 400, and the reason goes to the log.
What about the signature? This id_token doesn’t go through the browser: it comes from the provider to the shop. With HTTPS, OpenID Connect allows trusting that connection instead of the signature, and openid-client only checks it if you ask it to.
What the shop keeps: the sub
Section titled “What the shop keeps: the sub”Migration 008:
-- It can be missing (NULL): whoever only uses a password doesn't have one. UNIQUE: one sub, one-- account. With a single provider a column is enough; with several (Google, GitHub…), it would be-- a separate table with the provider and the sub of each one.ALTER TABLE users ADD COLUMN provider_sub text UNIQUE;The shop recognizes Marta by her sub, not by her email, which can change.
Who she is gets decided by userFromProvider, in src/users.ts:
const [withSub] = await db.select(columns).from(users).where(eq(users.providerSub, identity.sub));if (withSub) return { user: withSub };if (identity.email === undefined) return { error: 'no-email' };
const [withEmail] = await db .select(columns) .from(users) .where(sql`lower(${users.email}) = lower(${identity.email})`);if (withEmail) { if (!identity.emailVerified) return { error: 'email-not-verified' }; await db.update(users).set({ providerSub: identity.sub }).where(eq(users.id, withEmail.id)); return { user: withEmail };}- First, by
sub. If an account has it, that’s the one. - If not, by email: it’s linked to the account with that email, recording the
subin it, only if the provider says the email is verified. If not,409. - If there’s none, it’s created, without a password.
Why verified? Otherwise, anyone could create an account at the provider with ana@shop.example and get into Ana’s. In 2023, websites were found that fell for this with Microsoft accounts (nOAuth, by Descope).
From practice to Google
Section titled “From practice to Google”To use Google, the code doesn’t change: the four variables in .env do.
- In the Google Cloud console, you set up the consent screen (what Marta will see) and create an OAuth client ID for a web application.
- You register the exact callback URL. Google rejects any other: nobody can ask for the code to go to their website.
- The client ID and the secret it gives you go into
OIDC_CLIENT_IDandOIDC_CLIENT_SECRET, out of the code and out of Git. OIDC_ISSUER=https://accounts.google.com: the shop reads its/.well-known/openid-configurationand finds the rest.
Google accepts http://localhost for testing; in production, HTTPS. We haven’t tried it with a Google account.
Try it
Section titled “Try it”The goal: sign in as Marta with you playing the browser, see what the shop keeps, and check that a changed state and a stolen code are useless.
You attack your own shop, on your own computer: doing it against someone else’s system without permission is a crime.
Update your project
Section titled “Update your project”You start from your project from lesson 3. Install the shop’s library and, for development only, the provider’s:
1. Two packages
npm install openid-client@6.8.8npm install -D oauth2-mock-server@9.2.0What you will see:
added 2 packages, and audited 73 packages in 810ms
11 packages are looking for fundingrun `npm fund` for details
4 moderate severity vulnerabilities
To address all issues (including breaking changes), run:npm audit fix --force
Run `npm audit` for details.
added 2 packages, and audited 75 packages in 1s
11 packages are looking for fundingrun `npm fund` for details
4 moderate severity vulnerabilities
To address all issues (including breaking changes), run:npm audit fix --force
Run `npm audit` for details.-D records it in devDependencies: the practice provider never goes to production. The 4 vulnerabilities are drizzle-kit’s, as in lesson 3. The outputs are from Node 26.11.1 and PostgreSQL 18.6; your codes, tokens and times will be different.
Add the column in src/schema.ts (the marked lines):
// The table from migration 005. The unique index is on lower(email): a piece of SQL (sql`…`).export const users = pgTable( 'users', { id: integer().primaryKey().generatedAlwaysAsIdentity(), email: text().notNull(), passwordHash: text('password_hash'), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), // Migration 008: the sub of whoever comes in with the identity provider. providerSub: text('provider_sub').unique(), }, (table) => [uniqueIndex('users_email_unique').on(sql`lower(${table.email})`)],);Write db/migrations/008-provider.sql with the SQL above, and generate drizzle-kit’s snapshot as in lesson 3:
2. The migration
npm run db:generate -- --name=providernpm run db:migrateWhat you will see:
> shop-api@1.0.0 db:generate> drizzle-kit generate --name=provider
No config path provided, using default 'drizzle.config.ts'Reading config file '/Users/ana/backend-course/phase-3/shop-api/drizzle.config.ts'9 tablesapi_keys 5 columns 0 indexes 0 fkscategories 2 columns 0 indexes 0 fksidempotency_keys 6 columns 0 indexes 0 fksorders 5 columns 1 indexes 1 fksprocessed_events 2 columns 0 indexes 0 fksproduct_categories 2 columns 1 indexes 2 fksproducts 4 columns 0 indexes 0 fkssessions 4 columns 0 indexes 1 fksusers 5 columns 1 indexes 0 fks
[✓] Your SQL migration file ➜ drizzle/0005_provider.sql 🚀
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 008-provider.sqlusers now has 5 columns. If you get No schema changes, you didn’t save schema.ts.
Then:
- Create
src/provider.ts; adduserFromProvidertosrc/users.ts, the routes tosrc/contract.tsandsrc/v2.ts, and the variables tosrc/config.ts. Whatever you haven’t seen, copy it from the step. - Add the marked lines to your
.env. The practice provider accepts any id and secret:
# Copy this file as .env and change the values. .env isn't uploaded to Git: it's in .gitignore.PORT=3000LOG_LEVEL=info# A long text that's hard to guess. You can generate one with: openssl rand -hex 24ADMIN_TOKEN=change-this-to-a-long-token# The secret the shop shares with the payment gateway to sign the webhooks. A different one.WEBHOOK_SECRET=change-this-to-another-long-secret# The database: postgres://user:password@server:port/database. The password is the one you gave# the shop user when you created it.DATABASE_URL=postgres://shop:change-this-password@localhost:5432/shop# The identity provider (lesson 4). For practice, the one from npm run provider, on your computer:# it accepts any id and secret. With Google, the issuer is https://accounts.google.com, and Google# Cloud gives you the id and the secret when you register the shop (with the exact redirect URL# below).OIDC_ISSUER=http://localhost:9000OIDC_CLIENT_ID=shopOIDC_CLIENT_SECRET=change-this-to-the-provider-secretOIDC_REDIRECT_URI=http://localhost:3000/v2/session/provider/callback- Add the
providerscript topackage.json(the marked line):
{ "name": "shop-api", "version": "1.0.0", "private": true, "type": "module", "engines": { "node": ">=24" }, "scripts": { "start": "node --env-file-if-exists=.env src/server.ts", "dev": "node --env-file-if-exists=.env --watch src/server.ts", "test": "node --env-file=test/.env --test --test-concurrency=1", "check": "tsc --noEmit", "gateway": "node --env-file-if-exists=.env scripts/payment-gateway.ts", "db:migrate": "node --env-file-if-exists=.env scripts/migrate.ts", "db:seed": "node --env-file-if-exists=.env scripts/seed.ts", "db:many-orders": "node --env-file-if-exists=.env scripts/many-orders.ts", "db:generate": "drizzle-kit generate", "create-key": "node --env-file-if-exists=.env scripts/create-key.ts", "provider": "node scripts/provider.ts" }, "dependencies": { "@hono/node-server": "2.1.8", "@hono/zod-openapi": "1.6.3", "@hono/zod-validator": "0.9.1", "@scalar/hono-api-reference": "0.12.10", "drizzle-orm": "0.45.3", "hono": "4.13.18", "jose": "6.2.12", "openid-client": "6.8.8", "pg": "8.23.1", "pino": "10.4.0", "protobufjs": "8.8.0", "ws": "8.22.0", "zod": "4.6.7" }, "devDependencies": { "@types/node": "26.6.4", "@types/pg": "8.23.1", "@types/ws": "8.18.2", "drizzle-kit": "0.31.11", "oauth2-mock-server": "9.2.0", "typescript": "7.0.2" }}The provider and the tests come in this lesson’s folder; its test/.env brings the new variables:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/27-oauth.tar.gztar -xzf 27-oauth.tar.gzcd shop-apicp ../27-oauth/scripts/provider.ts scripts/cp ../27-oauth/test/*.ts ../27-oauth/test/.env test/If you get stuck, compare with 27-oauth. npm test should end with fail 0: the tests start their own provider.
Start the practice provider
Section titled “Start the practice provider”Open three terminals in the project folder. In the first one:
3. The provider, on localhost:9000
npm run providerWhat you will see:
> shop-api@1.0.0 provider> node scripts/provider.ts
Practice provider at http://localhost:9000Its configuration: http://localhost:9000/.well-known/openid-configurationIt’s oauth2-mock-server, a provider for testing: it doesn’t ask for a password, accepts any shop and always says that whoever signs in is this Marta. Never use it outside your computer. It stops with Ctrl + C.
// The person who "signs in" at the provider. sub is their identifier at the provider, the one that// doesn't change; email_verified: the provider has checked that the email is theirs.export const MARTA = { sub: 'provider-marta-0001', email: 'marta@example.com', email_verified: true, name: 'Marta Ruiz',};In the second terminal, npm start. If it says Configuration: OIDC_ISSUER: OIDC_ISSUER is missing, or it is not a URL, the variables are missing from your .env.
Be the browser, redirect by redirect
Section titled “Be the browser, redirect by redirect”curl doesn’t follow redirects unless you ask it to: that way you see each hop. In the third terminal:
4. The way there
curl -s -i -c cookies.txt localhost:3000/v2/session/providerWhat you will see:
HTTP/1.1 302 Foundlocation: http://localhost:9000/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fv2%2Fsession%2Fprovider%2Fcallback&scope=openid+email+profile&code_challenge=Ch9c9N8GdTZShksszI13sQVGixUft0MBv9zdfHgD4RI&code_challenge_method=S256&state=tG9PMk9P8rfqBoV9WX5LnTGKfShZD5EapZmoK4VYkf8&nonce=JlQCLmyIVu5ctyLCJlhPKBM2mpNaCkDqYRJViq8gUcc&client_id=shop&response_type=codevary: Originx-request-id: f28ae64c-a2d0-4a87-9b9e-4bbd72f37ba2set-cookie: provider=eyJzdGF0ZSI6InRHOVBNazlQOHJmcUJvVjlXWDVMblRHS2ZTaFpENUVhcFptb0s0VllrZjgiLCJub25jZSI6IkpsUUNMbXlJVnU1Y3R5TENKbGhQS0JNMm1wTmFDa0RxWVJKVmlxOGdVY2MiLCJ2ZXJpZmllciI6ImNXcThJdEQ1SWpqVTM0VUcwX3c4ZXBrTUNhdl9lNk9lczJYV0phWXJSOGsifQ; Max-Age=600; Path=/v2/session/provider; HttpOnly; Secure; SameSite=LaxDate: Wed, 14 Oct 2026 04:47:05 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunkedA 302 with location, the provider’s URL, and set-cookie, the three values in JSON and base64url: it starts with eyJ, like a JWT. If you get a 500, the provider isn’t running: in the server’s terminal you’ll see ECONNREFUSED.
So you don’t have to copy that URL by hand, start another sign-in and keep its URL in a shell VariableA name that holds a value to use later, such as price = 8.5. In JavaScript it’s created with const, if it won’t be swapped for another value, or with let, if it will.Go to definition:
5. The URL to the provider, parameter by parameter
START=$(curl -s -o /dev/null -w '%{redirect_url}' -c cookies.txt localhost:3000/v2/session/provider)echo "$START" | tr '?&' '\n\n'What you will see:
http://localhost:9000/authorizeredirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fv2%2Fsession%2Fprovider%2Fcallbackscope=openid+email+profilecode_challenge=Zxf0ILrALW2nn_jfQTLZnoptcAGbRUpltxG9TuOsJQEcode_challenge_method=S256state=tyEUmqHQGHOWPvWAA4W45S-XB3JXa1y3tqmmM2GHY6gnonce=0dDNwbkW8OW8EsQS-QgtjyVViaeRrsUWTGNtrfZjiSMclient_id=shopresponse_type=code-w '%{redirect_url}' writes only the address in location, and -o /dev/null throws away the rest. tr changes ? and & into line breaks (Phase 1’s pipes lesson).
state, nonce and code_challenge are different from the ones in step 4: each sign-in gets new ones, and the new cookie replaces the old one.
Now, what the browser would do: go to the provider.
6. At the provider
CALLBACK=$(curl -s -o /dev/null -w '%{redirect_url}' "$START")echo "$CALLBACK" | tr '?&' '\n\n'What you will see:
http://localhost:3000/v2/session/provider/callbackcode=dea35e6f-a945-46d7-87d3-b27cfd0efec1state=tyEUmqHQGHOWPvWAA4W45S-XB3JXa1y3tqmmM2GHY6gA real provider would show its sign-in page here. The practice one redirects to the shop right away, with a code and the state from step 5.
In the provider’s terminal:
/authorize: Marta Ruiz signs in. Back to http://localhost:3000/v2/session/provider/callback with code=dea35e6f-a945-46d7-87d3-b27cfd0efec1 and state=tyEUmqHQGHOWPvWAA4W45S-XB3JXa1y3tqmmM2GHY6g7. The way back
curl -s -i -b cookies.txt -c cookies.txt "$CALLBACK"What you will see:
HTTP/1.1 303 See Otherlocation: /v2/mevary: Originx-request-id: 582f3f27-6264-41b6-880f-1a24f05d1258set-cookie: provider=; Max-Age=0; Path=/v2/session/provider; HttpOnly; Secure; SameSite=Laxset-cookie: session=JLxhnpEfpHPRXXHjNUAaXVvTPYtx8VikfP0GJlxPMo4; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=LaxDate: Wed, 14 Oct 2026 04:47:05 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunked-b cookies.txt sends back the cookie from the way there. The shop has exchanged the code: a /token line shows up in the provider’s terminal. Two set-cookie: the one from the way there, deleted with Max-Age=0, and the session one from lesson 2.
8. Who you are
curl -s -w '\n' -b cookies.txt localhost:3000/v2/meWhat you will see:
{"type":"user","id":1,"email":"marta@example.com"}It’s account 1, the one Marta created with a password in lesson 1: her email is verified, and the shop has linked it. If your Marta has another id, it’s the one she got.
Marta’s row
Section titled “Marta’s row”9. Marta's row
psql -d shop -c 'SELECT id, email, provider_sub, password_hash IS NOT NULL AS has_password FROM users;'What you will see:
id | email | provider_sub | has_password----+-------------------+---------------------+--------------1 | marta@example.com | provider-marta-0001 | t(1 row)provider_sub has Marta’s sub, and has_password is t (true): Marta gets into the same account both ways. If you have the practice accounts, you’ll see more rows.
A changed state
Section titled “A changed state”Now you play the attacker: a way back with a state your browser didn’t keep.
10. Someone else’s state
START=$(curl -s -o /dev/null -w '%{redirect_url}' -c cookies.txt localhost:3000/v2/session/provider)CALLBACK=$(curl -s -o /dev/null -w '%{redirect_url}' "$START")TAMPERED=$(echo "$CALLBACK" | sed 's/state=.*/state=from-another-browser/')curl -s -w '\n' -b cookies.txt -c cookies.txt "$TAMPERED"curl -s -w '\n' -b cookies.txt -c cookies.txt "$CALLBACK"What you will see:
{"type":"https://shop.example/problems/provider-sign-in","title":"Could not sign in with the provider","status":400,"detail":"The provider's response is not valid, or this browser did not start it: start again"}{"type":"https://shop.example/problems/provider-sign-in","title":"Could not sign in with the provider","status":400,"detail":"The provider's response is not valid, or this browser did not start it: start again"}sed changes the state in the URL. The tampered way back gets a 400, and the server’s log says why: unexpected "state" response parameter value. The shop didn’t even call the provider: there’s no /token in its terminal.
What about the second one, with the right state? Also 400: the first one deleted the cookie.
A stolen code, without the verifier
Section titled “A stolen code, without the verifier”Now you play the shop, with PKCE by hand, and the code thief.
11. The code, without its verifier
V=$(openssl rand -base64 32 | tr '+/' '-_' | tr -d '=')C=$(printf '%s' "$V" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')REDIRECT_URI=http://localhost:3000/v2/session/provider/callbackCODE=$(curl -s -o /dev/null -w '%{redirect_url}' "localhost:9000/authorize?response_type=code&client_id=shop&scope=openid+email&redirect_uri=$REDIRECT_URI&state=1&nonce=n-0001&code_challenge=$C&code_challenge_method=S256" | sed 's/.*code=//; s/&.*//')curl -s -w '\n' -d grant_type=authorization_code -d client_id=shop -d redirect_uri=$REDIRECT_URI -d code=$CODE -d code_verifier=one-made-up-by-whoever-stole-the-code-0123456789 localhost:9000/tokenWhat you will see:
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"Bad Request","detail":"code_verifier provided does not match code_challenge"}Vis the verifier: 32 random bytes, in base64url.C, its challenge: the SHA-256 ofV, in base64url.CODE: you ask for a code with the challenge, andsedtakes it out of the callback URL.- The last
curldoes step 5 with the thief’s verifier.-dsends each piece of data in the body of aPOST.
The verifier doesn’t match the challenge, and there are no tokens. A limit of the practice provider: with no verifier at all, it gives out the tokens. A real one requires it if the way there carried a challenge (RFC 7636).
With the right verifier and a new code:
12. Marta’s id_token
CODE=$(curl -s -o /dev/null -w '%{redirect_url}' "localhost:9000/authorize?response_type=code&client_id=shop&scope=openid+email&redirect_uri=$REDIRECT_URI&state=1&nonce=n-0001&code_challenge=$C&code_challenge_method=S256" | sed 's/.*code=//; s/&.*//')curl -s -o tokens.json -d grant_type=authorization_code -d client_id=shop -d redirect_uri=$REDIRECT_URI -d code=$CODE -d code_verifier=$V localhost:9000/tokennode -p "JSON.parse(Buffer.from(require('./tokens.json').id_token.split('.')[1], 'base64url'))"What you will see:
{iss: 'http://localhost:9000',iat: 1791953239,exp: 1791956839,nbf: 1791953229,sub: 'provider-marta-0001',aud: 'shop',nonce: 'n-0001',email: 'marta@example.com',email_verified: true,name: 'Marta Ruiz'}tokens.json keeps the response: the access_token, the id_token and a token to renew them. node decodes the second part of the id_token, as you did with base64 in lesson 3.
There’s what the shop checks and uses: iss, aud (the shop’s id), your nonce, sub and email_verified. nbf (not before) says from when it’s valid. If you get Cannot read properties of undefined, look at the error in tokens.json: do steps 11 and 12 in the same terminal.
You have already seen it
Section titled “You have already seen it”- “Sign in with Google,” “with Apple” or “with GitHub.” It’s this flow. The screen that asks you for permission is step 3, and what it asks for are the scopes.
- The address bar. When you press the button, you see
accounts.google.com/…for a moment, withclient_id,redirect_uriandstate: the way there. - The apps with access to your account. Your Google account lists the permissions you gave, and that’s where you take them away.
- DevTools’ Network tab (Phase 2’s introduction). With “Preserve log” on, each redirect in a sign-in is a row.
Common mistakes
Section titled “Common mistakes”- Using the access_token as proof of who someone is. That’s what the id_token is for, once checked.
- Skipping the state, or always using the same one. The attacker’s way back gets in as if it were yours.
- Recognizing people by email, or linking accounts with an unverified email. Use the
sub, and only link withemail_verified. - Open callback URLs, or ones with wildcards. The code would end up wherever the attacker says.
- The client secret in the frontend or in Git. It goes in the server’s
.env.
Summary
Section titled “Summary”- OAuth 2.0 gives a website limited permission, the access_token, without it seeing your password. OpenID Connect adds who you are: the id_token, a JWT signed by the provider.
- The code flow with PKCE: the browser only carries a single-use code, and the shop exchanges it for the tokens in a direct request.
- PKCE makes a stolen code useless; the state ties the way back to the browser that started it, and the nonce ties the id_token to that sign-in.
- The shop recognizes people by the
sub, and links accounts by email only if it’s verified. - Moving to Google means changing the issuer, the client ID, the secret and the callback URL.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- RFC 6749: The OAuth 2.0 Authorization Framework.
- RFC 9700: Best Current Practice for OAuth 2.0 Security: why the code flow with PKCE.
- RFC 7636: Proof Key for Code Exchange.
- OpenID Connect Core 1.0: the id_token.
- OAuth 2.0 Cheat Sheet (OWASP).
- OpenID Connect at Google: how to register a website.
- openid-client and oauth2-mock-server: the lesson’s libraries.