BE5: Sign-in with OAuth 2 and OpenID Connect

Lesson 2 of 5 · reading 15–25 minutes; practice and project time is on the module page

The authorization code flow with PKCE

🎯You'll be able to

Follow each step of the authorization code flow with PKCE, the recommended way for web and mobile apps to get tokens.

🏠The everyday picture

At a hospital, you show your ID at reception and get a numbered slip. You take the slip to the pharmacy counter, which hands over the medicine only if the slip matches the one reception issued, and only once.

📘What it really is

📝A worked example

Input: npm run token in the kit. Steps you can watch:

  1. tools/get-token.js makes verifier = random 32 bytes, challenge = BASE64URL(SHA256(verifier)), and a random state.
  2. It prints a link: http://localhost:4100/authorize?response_type=code&client_id=tiffin-web&redirect_uri=http://localhost:4500/callback&scope=openid profile orders:read orders:write&state=...&code_challenge=...&code_challenge_method=S256.
  3. You choose "test customer 1"; the server redirects to http://localhost:4500/callback?code=...&state=....
  4. The tool checks state, then posts grant_type=authorization_code, the code, redirect_uri, client_id and code_verifier to /token.
  5. Expected output: a JSON response with access_token, id_token, refresh_token, expires_in: 600 and scope.

Try sending the same code twice: the second time the server answers invalid_grant, because codes work once.

🌍Where it's used

📝Case scenario

A team's mobile app uses the old implicit flow: the access token comes back in the redirect URL. Another app on the phone registers the same custom URL scheme and receives some users' tokens. With the code flow and PKCE, a stolen code is useless without the verifier, which never left the real app.

🖱️Try it

Run npm run token, sign in, and copy the access token. Then change one character of the code_verifier in tools/get-token.js and try again. Success: the first run gives tokens, the second gives invalid_grant with a PKCE message, and you can explain why.

⚠️Common mistakes

🛠️For your project

Your Project 1 demo shows a real token from npm run token being used against your API.

✅Quick check

What does PKCE protect against?

Show the answer

A stolen authorization code being exchanged for tokens by someone who doesn't have the code verifier.

Why must the app check state on the callback?

Show the answer

To make sure the response belongs to a sign-in it started, stopping forged or replayed callbacks.

← PreviousWho you are, and what you may do
ProLearners Assist