devHọc Dev

Week 1 - Day 3: OAuth 2.0 Authorization Code, PKCE/state/nonce and id_token validation

Week 1 – Day 3

This lesson combines 3 topics: OAuth 2.0 roles & the Authorization Code flow with a confidential client, PKCE, state, nonce: three bindings against attacks, id_token is a JWT: 7 checks & JWKS.

Learning Objectives

  • Name the 4 OAuth 2.0 roles correctly and identify which role the MemberPortal BFF plays
  • Understand why the BFF is a confidential client and which grant types that opens up
  • Know each step of the Authorization Code flow: /authorize → code → /oauth/token → id_token + access_token
  • Read the parameters of each request/response, and know which are required and which the BFF generates itself
  • Describe MemberPortal's two endpoints /auth/web/login and /auth/web/login-callback at the spec-table level
  • Understand what two things each of code_verifier, state, nonce binds together and which attack it blocks
  • Generate a code_verifier yourself with a CSPRNG and compute code_challenge = BASE64URL(SHA256(verifier)) without padding
  • Write the correct order of checks at the callback: state first, then code, then nonce once the id_token is available
  • Know the rule "wrong binding → delete SessionID1" and explain why
  • List the concrete vulnerabilities that arise when each binding is missing
  • Read the JWT structure header.payload.signature and explain why "readable" is not the same as "trustworthy"
  • List and correctly perform MemberPortal's 7 id_token checks: signature, iss, aud, exp, nonce, custom claim connection, conditional auth_time
  • Understand JWKS: kid, caching, rotation, retry when fetching JWKS fails
  • Know when auth_time must be checked and where the 600-second threshold comes from
  • Apply the principle accountNo comes from the id_token, not from the client and explain why

Part 1: OAuth 2.0 roles & the Authorization Code flow with a confidential client

1. What Days 1–2 left open, what Days 3–4 solve

Days 1–2 answered the second and third of the "three questions of every login spec": where does login state live (Redis, two kinds of session) and what happens on failure (401, which cookies to delete). The first question, who authenticates the user and how does the BFF trust that result, is still open.

MemberPortal does not check passwords itself. That job is delegated to the IdP (Auth0, with Keycloak as backup). The BFF only receives a "proof" and must validate that proof correctly. The proof is the id_token, and the way to obtain it is the Authorization Code flow of OAuth 2.0 (RFC 6749) as extended by OpenID Connect.

Day1–2Day3–4┌──────────────────────────┐┌────────────────────────────────────────┐│Whereisloginstate?││Whoauthenticates?WhatdoesBFFtrust?││-sess:{id}inRedis││-IdPauthenticates(Auth0/Keycloak)││-cookiesid/xsrf│──────▶│-BFFexchangescodeforid_token││Whatifitfails?││-BFFverifiesid_token(Part3)││-401,deletecookies││-PKCE/state/nonce(Part2)│└──────────────────────────┘└────────────────────────────────────────┘

2. The four OAuth 2.0 roles and who is who in MemberPortal

RFC 6749 defines 4 roles. A common mistake when writing specs is to call everything a "server", which leaves readers unsure which party holds the secret and which issues tokens.

Role (RFC 6749)DefinitionIn MemberPortal
Resource OwnerThe owner of the data, who consents to accessA customer with an online trading account
ClientThe application requesting access on behalf of the Resource OwnerThe NestJS BFF (not the browser!)
Authorization Server (AS)Authenticates the Resource Owner, issues code and tokensACME's Auth0 tenant (or Keycloak during failover)
Resource Server (RS)Holds the data, accepts access_tokensInternal API Gateway / Core API (via the BFF), Auth0 Management API (Day 4, Part 1)
┌───────────────────┐│ResourceOwner│customer,sittingatthebrowser└────────┬──────────┘│interactsthroughtheUser-Agent(browser/WebView)▼┌─────────────────────────────────────────────────────────────────────┐│User-Agent(Browser)──justa"pipe"carryingredirects──│└──────────┬──────────────────────────────────────────────┬───────────┘│302to/authorize│302backtocallback▼▼┌────────────────────────┐┌────────────────────────┐│AuthorizationServer│◀──POST/oauth/token│Client=BFF││(Auth0)│────id_token───────▶│holdsclient_secret│└────────────────────────┘│holdsRedissession│└───────────┬────────────┘│access_token/session▼┌────────────────────────┐│ResourceServer││(InternalAPIGW)│└────────────────────────┘

The common confusion: the browser is not the Client. In the BFF model, the browser only carries redirects and cookies (login_sid, then sid). It never sees code_verifier, client_secret, or id_token. Precisely because the Client is a BFF running on the server, we get section 3.

3. Confidential client vs public client

RFC 6749 section 2.1 splits Clients into two types by their ability to keep client_secret secret:

Confidential clientPublic client
Runs whereA server we control (BFF, backend)The user's device (SPA, mobile app, desktop)
Can keep client_secret?Yes (env/SSM, never sent to the browser)No (anyone can decompile/view the source)
Client authentication at /oauth/tokenclient_id + client_secretOnly client_id (+ mandatory PKCE)
Usable grantsauthorization_code, client_credentials, refresh_token, mfa (Auth0 extension)authorization_code + PKCE, refresh_token (with rotation)
MemberPortal examplesportal-web, portal-management, the step-up clientsNone: every client goes through the BFF

MemberPortal made the BFF a confidential client for three reasons stated explicitly in the spec:

  1. Tokens never leave the server. id_token/access_token exist only in BFF memory during the callback and (for step-up MFA) in Redis. The browser only has sid.
  2. client_credentials is available so the BFF can call the Auth0 Management API at startup (Day 4, Part 1). Public clients do not have this grant.
  3. PKCE is still used even though it is not mandatory for confidential clients. The OAuth 2.0 Security BCP recommends PKCE for every client; the cost is almost zero, and it blocks code injection. Day 3, Part 2 covers this in detail.

Self-check question: if tomorrow the mobile team wants to call Auth0 directly from the native app without going through the BFF, are they a public or a confidential client? Can they use client_credentials? Why?

4. Grant types and MemberPortal's choices

grant_typeUsed byUser interaction?ReturnsMemberPortal
authorization_codeClients whose users log in through a browserYescode → id_token, access_token, (refresh_token)portal-web, all step-up clients
client_credentialsMachine to machine, no userNoaccess_token for the client itselfportal-management (calls the Management API)
refresh_tokenClients that want to renew an access_tokenNoNew access_tokenNot used: the BFF uses a Redis session with its own TTL, no refresh token needed
http://auth0.com/oauth/grant-type/mfa-otp and the mfa-* familyClients that need to call the MFA API after authenticationYesaccess_token with scopes enroll, read:authenticatorsstepup-password-web, stepup-password-native (Day 7, Part 1)
Implicit (response_type=token)Legacy SPAsYesToken in the URL fragmentNot used, removed in OAuth 2.1
Password grant (ROPC)Apps that collect user/pass and send them straight to the IdPYesTokenNot used, lets the app see the password

Two design questions the MemberPortal spec answers explicitly, and which you should imitate:

  • Why no refresh_token? Because the "logged-in session" is the Redis session sess:{id} with TTL SESSION_TTL; after login the access_token from the IdP is not used to call any Resource Server (the Internal API Gateway trusts the BFF session, not the Auth0 token). Keeping a refresh_token only adds one more thing to protect.
  • Why client_credentials when authorization_code already exists? Because the BFF has work to do outside the context of a user (reading user metadata through the Management API, changing the passkey cancel URL...). The logged-in user's token does not have enough permissions and does not exist when the BFF starts.

5. The Authorization Code flow step by step

This is the backbone of /auth/web/login → /auth/web/login-callback. Remember the four "legs" and the data passing through each.

sequenceDiagram
    participant B as Browser
    participant BFF as BFF (Client)
    participant AS as Auth0 (AS)
    B->>BFF: GET /auth/web/login?successUrl=/dashboard
    Note over BFF: generate state, nonce,<br/>code_verifier (CSPRNG)<br/>store login:{sid1} in Redis
    BFF-->>B: 302 Location: https://login.example.com/authorize?...<br/>(Set-Cookie login_sid)
    B->>AS: GET /authorize?client_id&redirect_uri&response_type=code<br/>&scope&state&nonce&code_challenge(&method=S256)
    Note over AS: user enters password
    AS-->>B: 302 Location: https://portal.example.com/auth/web/<br/>login-callback?code=AUTHZ_CODE&state=STATE
    B->>BFF: GET /auth/web/login-callback?code&state (cookie login_sid)
    Note over BFF: read login:{sid1}, compare state
    BFF->>AS: POST /oauth/token<br/>grant_type=authorization_code<br/>code, redirect_uri,<br/>client_id, client_secret,<br/>code_verifier
    AS-->>BFF: { id_token, access_token,<br/>expires_in, token_type }
    Note over BFF: verify id_token (Part 3)<br/>delete login:{sid1}<br/>create sess:{sid2} + xsrfToken
    BFF-->>B: 302 Location: successUrl<br/>Set-Cookie: sid=sid2#59; xsrf=...#59; uid=...

5.1 Leg 1: the BFF prepares and redirects to /authorize

Parameters the BFF attaches to the /authorize URL (RFC 6749 §4.1.1 + OIDC Core §3.1.2.1 + RFC 7636):

ParameterRequiredMemberPortal valueGenerated byNotes
response_typeYescodefixedOnly receive a code, never a token directly
client_idYesid of portal-webenv IDP_CLIENT_IDPublic, not a secret
redirect_uriYes (OIDC)https://{BFF_DOMAIN}/auth/web/login-callbackfixed per envMust exactly match the allow-list in Auth0
scopeYesopenid profilefixedopenid is required to receive an id_token
stateRecommended (BFF: required)CSPRNG stringBFFStored in login:{id}, compared at the callback
nonceRecommended (BFF: required)CSPRNG stringBFFStored in login:{id}, compared with the nonce claim
code_challengeYes (PKCE)BASE64URL(SHA256(code_verifier))BFFcode_verifier is stored in login:{id}
code_challenge_methodYes (PKCE)S256fixedNever use plain
connectionIdP-specificUsername-Passwordfixed per clientAuth0-specific parameter that selects the connection
promptNoempty (web login) / login (step-up)per flowForces the IdP to re-authenticate; always paired with max_age so auth_time can be checked (Day 3, Part 3)
max_ageNoempty (web login) / 600 (step-up)per flowForces the IdP to issue the auth_time claim (OIDC Core §3.1.2.1: with max_age, auth_time is REQUIRED; without it, only OPTIONAL)

Generating state, nonce, code_verifier and storing SessionID1 (login:{id}) is exactly the "data stored in the data store table" learned in Day 2, Part 1. If you forget why there are two kinds of session, look at the diagram again: login:{sid1} lives exactly from leg 1 to leg 3 and is then deleted; sess:{sid2} is born in leg 4.

5.2 Leg 2: the IdP authenticates and returns a code

Auth0 shows Universal Login, checks the password, checks the account type via the custom DB (Day 6, Part 2), then 302s back to redirect_uri with:

SuccessFailure
?code=<authorization code>&state=<state>?error=access_denied&error_description=...&state=<state>

The code is a short-lived string (by default Auth0 expires it after a few minutes), single-use, and can only be exchanged by a client with the right client_secret and the right code_verifier. The error branch is handled in Day 4, Part 2.

5.3 Leg 3: the BFF exchanges the code for tokens at /oauth/token

This is a server-to-server request; the browser is not involved. The body is application/x-www-form-urlencoded (Day 1, Part 2 mentioned why the token endpoint accepts a form, not JSON).

POST /oauth/token HTTP/1.1
Host: login.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&client_id=<IDP_CLIENT_ID>
&client_secret=<IDP_CLIENT_SECRET>
&code=<code from the callback>
&redirect_uri=https%3A%2F%2Fportal.example.com%2Fauth%2Fweb%2Flogin-callback
&code_verifier=<code_verifier taken from login:{id}>

Successful response:

{
  "access_token": "<opaque or JWT>",
  "id_token": "<JWT: header.payload.signature>",
  "token_type": "Bearer",
  "expires_in": 86400
}

The MemberPortal spec states: retry /oauth/token at most 2 times on 5xx/timeout; on a 4xx error (e.g. invalid_grant because the code expired) do not retry, delete login:{id}, and go to "Login failed".

5.4 Leg 4: verify and issue the session

The BFF verifies the id_token against the 7 checks (Day 3, Part 3), takes sub and the custom claim https://claims.example.com/account_no, calls the Account Attribute API and the Login Status API (Day 6, Part 2), and only then:

  1. Deletes login:{sid1}.
  2. Generates a new sid2 with a CSPRNG, generates an xsrfToken, stores sess:{sid2} with TTL SESSION_TTL.
  3. Sets the sid, xsrf, uid cookies; 302 to successUrl.

The order "verify → call business APIs → only then create the session" is deliberate: if sess were created first and a business API then failed, the spec would need an extra branch to delete the session. Creating it last means the error branch only needs "do not set cookies".

6. MemberPortal's two endpoints at the spec-table level

Day 7, Part 3 teaches the full format. Here you get a preview of a condensed version to connect theory with a real spec.

6.1 GET /auth/web/login

Overview: start the login sequence, redirect the user to the IdP.

LocationItemRequiredValue / Rule
querysuccessUrlNoAbsolute URL with the same origin https://{BFF_DOMAIN} (compare scheme + host + port, reject http://); invalid → use https://www.example.com/
queryfailureUrlNoSame as above
query_glNoTracking parameter, appended to successUrl with ? or &
cookiesidNoIf a valid sess:{id} already exists → 302 straight to successUrl, skip the IdP

Processing details:

  • If isOpe=true (operator mode) → 400 (Day 7, Part 2).
  • Select the IdP: Auth0 or Keycloak according to ALT_IDP_ENABLED + the Auth Health API (Day 6, Part 3); write idProvider into the session.
  • Generate state, nonce, code_verifier (CSPRNG); compute code_challenge.
  • Create login:{sid1} with TTL SESSION_LOGIN_TTL and the fields: state, nonce, codeVerifier, successUrl, failureUrl, idProvider, channel=Web.
  • Set-Cookie login_sid=sid1 (Secure, HttpOnly, Lax); 302 to /authorize with the parameters from section 5.1.

6.2 GET /auth/web/login-callback

LocationItemRequiredValue / Rule
cookielogin_sidYesMust point to a live login:{id}; missing → "Login failed"
querystateYesMust equal the state in login:{id}
querycodeYes (when there is no error)Exchanged at /oauth/token
queryerror, error_descriptionNoIf error is present → screen mapping (Day 4, Part 2)

Processing details (condensed):

  • No login:{id} → "Login failed", delete nothing (there is nothing to delete).
  • Wrong state → delete login:{id}, "Login failed".
  • error present → delete login:{id}, map by error/error_description.
  • Missing code → delete login:{id}, "Login failed".
  • Token request (retry ≤ 2 times on 5xx/timeout) → fail: delete login:{id}, "Login failed".
  • Verify id_token (7 checks) → fail: delete login:{id}, "Login failed".
  • Account Attribute API / Login Status API → per Day 6, Part 2.
  • Success: delete login:{id}, create sess:{sid2}, set cookies, 302 successUrl.

Important observation: every error branch after login:{id} has been read deletes it. That is the "single-use login sequence" rule: an attacker cannot try multiple state/code values against the same session sequence.

7. Common mistakes when writing an Authorization Code flow spec

MistakeConsequenceHow MemberPortal avoids it
Writing "the browser calls /oauth/token"Readers assume a public client; the secret leaksThe diagram clearly shows the browser only carries redirects
Omitting redirect_uri from the token requestAuth0 rejects with invalid_grant when it differs from /authorizeThe token request parameter table includes redirect_uri
scope without openidNo id_token, only an opaque access_tokenFixed to openid profile
Using code_challenge_method=plainPKCE is pointless if /authorize is loggedFixed to S256
Not stating that code is single-useTesters do not understand why refreshing (F5) the callback failsStated explicitly + an invalid_grant branch
Creating the logged-in session before verification finishesExtra cleanup branches needed, easy to forgetCreating sess is the last step
Not stating what the access_token is used forDevelopers use the access_token to call the Internal API GWStated explicitly: after login, the web login access_token is not used anymore

Part 2: PKCE, state, nonce: three bindings against attacks

1. Why the Authorization Code flow needs "bindings"

In Day 3, Part 1, the flow goes through two redirects via the browser. Each redirect is a moment where the BFF loses control: values in the URL can be injected, altered, or replayed by an attacker. RFC 6749 section 10 and the OAuth Security BCP list three classes of attack corresponding to three gaps:

(1)codeinterception/injection(2)CSRFonthecallback▼▼Browser──/authorize──▶Auth0──302code+state──▶Browser──callback──▶BFF──/oauth/token──▶Auth0│▼id_token(3)id_tokenreplay

The three values the BFF generates at /auth/web/login are the three "strings" that tie the legs together so nobody can get in between:

ValueBinds what to whatBlocksChecked where
code_verifier / code_challenge (PKCE)code ↔ the client that started the flowAuthorization code interception, code injectionAuth0 checks at /oauth/token
statecallback ↔ SessionID1 (login:{id}) in the user's browserCSRF on the callback (login CSRF, session swapping)BFF checks at the start of the callback
nonceid_token ↔ the original /authorize requestid_token replayBFF checks while verifying the id_token

All three are stored in login:{id} (SessionID1) and bound to the browser through the cookie login_sid=sid1. That is why Day 2, Part 1 stresses that the login sequence needs a session: without a place to store them, there is nothing to compare against.

2. PKCE: binding the code to the client that started the flow

2.1 The attack to block

The code travels in the redirect URL back to redirect_uri. On mobile, a malicious app can register the same custom scheme; on the web, the code can leak through proxy logs, the Referer, or browser history. If anyone holding the code could exchange it for tokens, the code would be no different from a token.

With a confidential client, the attacker also needs the client_secret. But there is a variant, code injection: the attacker obtains their own code (by logging in with the attacker's account) and injects it into the victim's callback; the victim is logged in to the attacker's account without realizing it, and the attacker can read any data the victim enters afterwards. The client_secret cannot block this because both go through the legitimate BFF. PKCE + state can.

2.2 How it works (RFC 7636)

/auth/web/login/authorize/oauth/token┌──────────────────────────┐┌───────────────────┐┌────────────────────────┐│code_verifier=││code_challenge=││code_verifier(orig.)││CSPRNG32bytes││BASE64URL(││││→base64url(43chars)│──────▶│SHA256(verifier)││Auth0recomputesSHA256││storeinlogin:{id}││)+method=S256││compareswiththe││││Auth0storesit││storedchallenge││││withthecode││≠→invalid_grant│└──────────────────────────┘└───────────────────┘└────────────────────────┘

Only the party holding the original code_verifier can exchange the code. An attacker who intercepts the code and code_challenge (in the URL) gains nothing because SHA-256 is one-way. With code injection: the attacker's code is bound to the attacker's code_challenge, the BFF sends the code_verifier taken from the victim's login:{id} → no match → Auth0 returns invalid_grant.

2.3 Generating it correctly per the spec

RFC 7636 §4.1: code_verifier is a 43–128 character string from the set [A-Z a-z 0-9 - . _ ~]. A simple and correct way: 32 random bytes → base64url → 43 characters.

§4.2: code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))), without = padding.

import { randomBytes, createHash } from 'crypto';

/** Secure random string, base64url without padding. 32 bytes → 43 characters. */
export function secureRandomString(bytes = 32): string {
  return randomBytes(bytes).toString('base64url'); // Node ≥ 15.7 supports 'base64url'
}

export function generatePkce(): { codeVerifier: string; codeChallenge: string } {
  const codeVerifier = secureRandomString(32);
  const codeChallenge = createHash('sha256')
    .update(codeVerifier, 'ascii')
    .digest('base64url'); // padding already removed and +/ replaced with -_
  return { codeVerifier, codeChallenge };
}

// Manual equivalent if the runtime does not have 'base64url' yet:
export function toBase64Url(buf: Buffer): string {
  return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

The MemberPortal spec has a dedicated "How to generate PKCE" section in the common processes file, stating all three points explicitly: number of bytes, alphabet, padding removed. People writing a new spec often just write "generate PKCE per RFC 7636", and then each developer does it differently (some use hex, some keep the padding); a 64-character hex string is still valid, but it makes cross-team testing harder to reconcile.

2.4 Why a confidential client still uses PKCE

RFC 7636 was written for public clients, but the OAuth 2.0 Security BCP §2.1.1 recommends PKCE for every client, and OAuth 2.1 makes it mandatory. The reasons for a BFF:

  • It blocks code injection (section 2.1), which client_secret cannot.
  • If part of the flow is later moved to a public client (a native app), the procedure stays the same.
  • Cost: one SHA-256 and one field in Redis.

3. state: binding the callback to the browser that started the flow

3.1 The attack to block: CSRF on the callback

The attacker logs in themselves, stops at the step where the code is received (without letting their own browser call the callback), and sends the victim the link https://portal.example.com/auth/web/login-callback?code=<attacker code>&state=<anything>. If the BFF does not check state, the victim clicks it and ends up logged in to the attacker's account (login CSRF / session swapping). Combined with the code injection in section 2.1, this is exactly the scenario that PKCE + state block together.

3.2 How it works

VictimbrowserBFFcookielogin_sid────────────────────────▶login:{sid1}.state="S_victim"GETcallback?code=X&state=S_attacker───▶compare"S_attacker"≠"S_victim"→deletelogin:{sid1},"Loginfailed"

state is a CSPRNG value stored in login:{id}; login:{id} is bound to the browser through the login_sid cookie (HttpOnly). The attacker cannot read the victim's cookie and does not know the victim's state → cannot assemble a valid link.

3.3 Rules in the MemberPortal spec

  • state is the first check in the callback, before even looking at whether there is an error or a code.
  • Wrong state → delete login:{id} → "Login failed". Without deletion an attacker could brute-force state against the same session (although a 256-bit space makes this theoretically pointless, the "single-use" rule keeps the model simple).
  • Missing login_sid cookie or login:{id} past its TTL → "Login failed", nothing to delete.
  • Do not use state to carry business data (successUrl, channel...). That data lives in login:{id}. Some old guides suggest encoding successUrl into state; this forces the BFF to sign/encrypt state and opens the door to open redirects if done wrong. With a session in place, state only needs to be a random string.

Self-check question: if you drop the login_sid cookie in leg 1 and instead put sid1 into state itself (state = sid1), what still holds and what breaks?

4. nonce: binding the id_token to the original request

4.1 The attack to block: id_token replay

Suppose the attacker obtains a valid id_token of the victim (from logs, from another client, from an earlier leak). The attacker may try to "slip" that token into their own flow so the BFF believes the person logging in is the victim. With the Authorization Code flow over a server-to-server channel this scenario is much harder than with the Implicit flow, but OIDC Core still requires nonce so that an id_token is valid exactly once, for exactly one session.

4.2 How it works (OIDC Core §3.1.2.1, §3.1.3.7 item 11)

/auth/web/login/authorizeid_tokenpayload┌────────────────────┐┌────────────────────┐┌───────────────────────┐│nonce=CSPRNG│──────▶│&nonce=N│──────▶│{...,"nonce":"N"}││storelogin:{id}││Auth0keepsitand││BFFcheckslogin:{id}│└────────────────────┘│embedsinid_token││≠→verifyfail│└────────────────────┘└───────────────────────┘

In Day 3, Part 3, nonce is check number 5 of the 7 id_token checks. Wrong → delete login:{id}, "Login failed", like every other verification error.

4.3 nonce vs state, two things that are often confused

statenonce
LayerOAuth 2.0OpenID Connect
Where it appears on returnQuery string of the callbackClaim inside the id_token
Who reads itBFF, before exchanging the codeBFF, after exchanging the code
BindsCallback ↔ browser sessionid_token ↔ authorize request
Can they share one value?Technically yes; MemberPortal generates them separately so each value only appears in one channel (query vs token)

5. Order of checks at the callback and the "missing binding, resulting hole" table

5.1 Order

GET/auth/web/login-callback?code&state&error&error_description(cookielogin_sid)│├─1.cookielogin_sid→doeslogin:{id}exist?──no──▶"Loginfailed"(deletenothing)│├─2.state==login:{id}.state?──no──▶deletelogin:{id}→"Loginfailed"│├─3.errorpresent?──yes─▶deletelogin:{id}→screenmapping(Day4,Part2)│├─4.codepresent?──no──▶deletelogin:{id}→"Loginfailed"│├─5.POST/oauth/tokenwithcode_verifierfromlogin:{id}│Auth0checksPKCE──invalid_grant─▶deletelogin:{id}→"Loginfailed"│├─6.verifyid_token,includingnonce==login:{id}.nonce──wrong─▶deletelogin:{id}→failed│└─7....businesslogic(Day6,Part2)→deletelogin:{id},createsess:{sid2}

Why does state come before error? Because an error response from the IdP must also be a response of this flow. If error were checked first, an attacker could force anyone to see a "Under maintenance" or "Account restricted" screen with just a link, without the correct state. Checking state first turns every fake link into a generic "Login failed".

5.2 Missing binding, resulting hole

MissingExploitation scenarioSeverity for a confidential BFF client
No PKCECode injection: the attacker injects their own code into the victim's callback (also requires no state check, or tricking the victim into starting a flow and swapping the code midway through a malicious proxy/extension)Medium. client_secret blocks plain interception but not injection
No stateLogin CSRF: the victim clicks the attacker's callback link → logged in to the attacker's account; everything the victim enters (payee account numbers, documents) is readable by the attackerHigh. This is the most common vulnerability in OIDC audits
No nonceReplay an old id_token into a new session; with the code flow it must be combined with a token leak elsewhereLower, but OIDC requires the check once it has been sent
state present but login:{id} not deleted on mismatchUnlimited retries against the same session sequenceLow, but breaks the single-use rule
state/nonce/verifier generated with Math.random()The next value can be guessed after a few samples → a valid callback link can be builtHigh. As Day 2, Part 1 said: only use a CSPRNG
state stored in a plain cookie instead of the server sessionAttacker sets a cookie from another subdomain (cookie tossing) to force the stateMedium; MemberPortal avoids it by using Redis

6. How to write this part in the spec

The MemberPortal spec moves shared algorithms into a "common processes" file and endpoints just link to them. Condensed template:

Common: Generate a secure random string

  • Use the runtime's CSPRNG (crypto.randomBytes), 32 bytes, base64url encoded, no padding. Applies to: state, nonce, code_verifier, Session ID, xsrfToken.

Common: Generate PKCE

  • code_verifier per "Generate a secure random string".
  • code_challenge = BASE64URL(SHA256(ASCII(code_verifier))), strip trailing =, replace +→-, /→_.
  • code_challenge_method = S256.

Endpoint /auth/web/login: data stored in the data store

KeyFieldSourceNotes
login:{sid1}stateCommon: random stringCompared at callback step 2
nonceCommon: random stringCompared with the nonce claim (id_token check 5)
codeVerifierCommon: PKCESent to /oauth/token
successUrl, failureUrlQuery (validated)Not put into state
idProviderIdP selection (Day 6, Part 3)auth0 / keycloak
channelFixed Web
TTLSESSION_LOGIN_TTLEnv

Endpoint /auth/web/login-callback: processing details (first part)

  • Get login:{sid} from the login_sid cookie. Missing → go to "Login failed".
  • Compare the state query with login:{sid}.state. Different → delete login:{sid}, go to "Login failed".
  • (next: handle error, code, the token request, verify id_token with nonce...)

Writing it this way lets readers answer "where is value X generated, where is it stored, where is it checked" immediately by looking at a table.

Part 3: id_token is a JWT: 7 checks & JWKS

1. What an id_token is and why the BFF must verify it itself

Day 3, Part 1 ended with the BFF receiving an id_token from /oauth/token. Many people stop here with the argument: "the token arrives over a server-to-server TLS channel from Auth0, with a client_secret, so it must be genuine". OIDC Core §3.1.3.7 still requires that the Client MUST validate the id_token, and so does the MemberPortal spec, because:

  • The TLS channel proves "the packet came from the Auth0 server", not "this token is meant for this client, for this session, and is still valid".
  • With a backup IdP (Keycloak, Day 6, Part 3), the BFF must be sure the token comes from the same IdP that started the flow.
  • Verification is the only place where nonce is checked (Day 3, Part 2).
  • If in the future tokens arrive through another channel (a native app uploading a token), the whole verification logic is already in place.
id_token = BASE64URL(header) . BASE64URL(payload) . BASE64URL(signature)

header  { "alg": "RS256", "typ": "JWT", "kid": "k2024-09" }
payload { "iss": "https://login.example.com/",
          "sub": "auth0|64f1...",
          "aud": "<client_id of portal-web>",
          "iat": 1726300000, "exp": 1726386400,
          "nonce": "Qn3...",
          "auth_time": 1726299990,
          "https://claims.example.com/account_no": "1234567",
          "https://claims.example.com/connection": "Username-Password" }
signature = RSASSA-PKCS1-v1_5(SHA256(header.payload), Auth0's private key)

Readable does not mean trustworthy. The payload is just base64url, anyone can decode it. What makes a token trustworthy is a signature that matches the IdP's public key and claims that match the BFF's expectations. Missing either one is a vulnerability.

2. MemberPortal's seven id_token checks

The MemberPortal spec places this table in the common processes file ("id_token validation") and every callback (web login, step-up, logout callback if needed) links to it. The table is mapped against OIDC Core §3.1.3.7:

#CheckWhat is checkedSource of the expected valueOIDC CoreOn failure
1SignatureVerify the signature with the public key from the IdP's JWKS by kid; alg must be RS256 (allow-list)JWKS URI of the idProvider in login:{id}§3.1.3.7 item 6Delete login:{id}, "Login failed"
2issExactly equals the issuer of the IdP that started the flowConfiguration per idProvider (https://login.example.com/ or the Keycloak issuer)item 2same as above
3audContains the client_id of the client in use (portal-web, or the corresponding step-up client)Env IDP_CLIENT_ID per clientitem 3same as above
4expexp > current time (small clock skew allowed, e.g. 60s)BFF clockitem 9same as above
5nonceEquals login:{id}.nonceSessionID1item 11same as above
6Custom claim connectionhttps://claims.example.com/connection is in the client's set of valid connections (portal-web: Username-Password, Passkey-Login; step-up clients: the corresponding connection). From it derive usedPasskey = (connection == 'Passkey-Login')IdP client tableMemberPortal-specificsame as above
7auth_time (conditional)Only when the /authorize request has max_age (step-up sends prompt=login&max_age=600): now - auth_time ≤ 600s. Without max_age the IdP is not required to issue auth_timeFlow configurationitem 13same as above

Three notes for spec writers:

  1. No check is "optional" once you have sent it: if the flow sends nonce, you must check nonce; if it sends max_age, you must check auth_time. The MemberPortal spec labels check 7 "conditional", not "optional".
  2. Every verification error goes down the same branch: delete SessionID1, show the "Login failed" screen, do not reveal externally which error occurred (anti-probing), but internal logs have a specific error code for tracing (Day 7, Part 3).
  3. iat, sub, azp are not in the mandatory table, but sub is used (written into sess), and OIDC requires sub to be present; a missing sub means the token is invalid. As for azp: OIDC Core §3.1.3.7 items 4–5 recommend (SHOULD) that if the token has an azp claim it should be checked against the client_id; jose.jwtVerify does not check azp by itself, so MemberPortal's code adds one more line (skipped only when aud is single-valued and the IdP does not issue azp, and this must be stated in the spec).

3. Check 1 in depth: JWKS, kid, caching and retry

3.1 What JWKS is

The IdP publishes its set of public keys at .../.well-known/jwks.json (Auth0) or .../protocol/openid-connect/certs (Keycloak). Each key has a kid. The JWT header says which kid signed it; the BFF picks the matching key to verify.

Auth0JWKSBFF┌──────────────────────────────┐┌─────────────────────────────────────┐│{"keys":[││1.readheader.kid="k2024-09"││{"kid":"k2024-09",│◀───────│2.lookupintheJWKScache││"kty":"RSA","n":...,│GET│-found→verify││"e":"AQAB","alg":││-none→refetchJWKS(retry≤2)││"RS256","use":"sig"},││-stillnone→verifyfail││{"kid":"k2024-03",...}││3.RS256verify(header.payload,key)││]}│└─────────────────────────────────────┘└──────────────────────────────┘

3.2 MemberPortal's rules

  • Cache at startup: the BFF loads Auth0's JWKS, and Keycloak's if ALT_IDP_ENABLED=true, during the boot process (Day 4, Part 1 covers boot). The callback does not have to wait on the network.
  • Refetch on an unknown kid: when the IdP rotates keys it adds a new kid. On a kid not in the cache → reload the JWKS once, retrying at most 2 times on 5xx/timeout. Still missing → fail.
  • Do not trust alg in the header: allow-list RS256. Tokens with alg: none or HS256 are rejected before a key is even touched. This is a classic vulnerability ("alg confusion"): the library reads alg from the header, the attacker changes it to HS256 and signs with the (public) public key used as the secret.
  • Do not load JWKS from a URL in the token (jku header). The JWKS URL is fixed configuration per idProvider.

3.3 Sample code with jose

import { createRemoteJWKSet, jwtVerify, JWTPayload } from 'jose';

// Created once at boot per IdP; jose caches and refetches automatically on an unknown kid.
const jwksByProvider = {
  auth0: createRemoteJWKSet(new URL('https://login.example.com/.well-known/jwks.json'), {
    cooldownDuration: 30_000,     // avoid refetch storms
    cacheMaxAge: 10 * 60_000,     // periodic refresh
  }),
  keycloak: createRemoteJWKSet(new URL('https://kc.example.internal/realms/acme/protocol/openid-connect/certs')),
};

const issuerByProvider = {
  auth0: 'https://login.example.com/',
  keycloak: 'https://kc.example.internal/realms/acme',
};

const CLAIM_NS = 'https://claims.example.com/';
const AUTH_TIME_MAX_AGE_SEC = 600;

export interface VerifyContext {
  idProvider: 'auth0' | 'keycloak';
  clientId: string;              // client in use (portal-web, stepup-*)
  expectedNonce: string;         // login:{id}.nonce
  allowedConnections: string[];  // set of valid connections for the client (client table)
  maxAgeSec?: number;            // did the request have max_age? (step-up: 600)
}

export async function verifyIdToken(idToken: string, ctx: VerifyContext): Promise<JWTPayload> {
  // Checks 1-4: signature (kid → JWKS), alg allow-list, iss, aud, exp
  const { payload } = await jwtVerify(idToken, jwksByProvider[ctx.idProvider], {
    algorithms: ['RS256'],
    issuer: issuerByProvider[ctx.idProvider],
    audience: ctx.clientId,
    clockTolerance: 60,
  });

  // Check 5: nonce
  if (payload.nonce !== ctx.expectedNonce) throw new Error('ID_TOKEN_NONCE_MISMATCH');

  // Check 6: custom claim connection is in the client's valid set
  const connection = payload[`${CLAIM_NS}connection`] as string | undefined;
  if (!connection || !ctx.allowedConnections.includes(connection)) {
    throw new Error('ID_TOKEN_CONNECTION_MISMATCH');
  }

  // Check 7: auth_time, only when the request had max_age (step-up: prompt=login&max_age=600)
  if (ctx.maxAgeSec !== undefined) {
    const authTime = payload.auth_time as number | undefined;
    const now = Math.floor(Date.now() / 1000);
    if (typeof authTime !== 'number' || now - authTime > ctx.maxAgeSec) {
      throw new Error('ID_TOKEN_AUTH_TIME_TOO_OLD');
    }
  }

  // azp: jose does not check it; OIDC Core §3.1.3.7 (4)-(5)
  if (payload.azp !== undefined && payload.azp !== ctx.clientId) {
    throw new Error('ID_TOKEN_AZP_MISMATCH');
  }

  if (typeof payload.sub !== 'string') throw new Error('ID_TOKEN_SUB_MISSING');
  return payload;
}

Note for the spec: internal error codes (ID_TOKEN_NONCE_MISMATCH...) only go into logs with bffErrCode; users always see "Login failed".

4. Check 7 in depth: prompt=login and auth_time

4.1 The problem

The IdP keeps its own SSO session (a cookie on the Auth0 domain). If the user logged in to Auth0 30 minutes ago for another ACME app, calling /authorize again will not ask for a password and will return a code immediately. For a normal web login, that is the desired convenience. For step-up authentication (Day 7, Part 1), we need the user to actually re-authenticate right now before withdrawing money; an old SSO session is not enough.

4.2 A two-step solution

  1. Send prompt=login&max_age=600 to /authorize: prompt=login asks the IdP to force re-authentication; max_age forces the IdP to issue the auth_time claim in the id_token (OIDC Core §2: auth_time is only REQUIRED when the request has max_age, otherwise OPTIONAL). Without max_age, step 2 has nothing to check.
  2. Do not trust step 1 blindly: check the auth_time claim (the time the user last authenticated, OIDC Core §2) against the current time. MemberPortal chose a threshold of 600 seconds.
now=12:00:00┌──────────────────────────────┬──────────────────────────────┐│auth_time=11:59:30│auth_time=11:20:00││now-auth_time=30s≤600│now-auth_time=2400s>600││→accepted│→IdPskippedprompt,oran│││oldtoken→verifyfail│└──────────────────────────────┴──────────────────────────────┘

Why 600 seconds and not 5 or 60? Because the user may take a few minutes to enter a password, OTP, or passkey; the threshold must be wider than a reasonable interaction time but much narrower than the IdP's SSO session TTL (usually hours). 600s also matches the fixed TTL of the stepup:{id} child session, keeping the time model consistent.

4.3 Why web login does not send prompt

MemberPortal's web login used to send prompt=login too. Then the business requirement changed: customers already logged in to another ACME app should not have to re-enter their password when entering the portal. The spec removed prompt/max_age from the web login endpoint but kept the auth_time check logic in the common process under the condition "only when the request has max_age". Lesson: write common processes by condition, not by endpoint name, so a change in one flow does not break another.

5. Custom claims and the principle "accountNo comes from the id_token"

5.1 Namespaced claims

OIDC Core §5.1.2 recommends that self-defined claims use URL-style names to avoid colliding with standard claims. Auth0 requires a namespace for custom claims in the id_token. MemberPortal uses:

ClaimMeaningWho adds it to the tokenThe BFF uses it to
https://claims.example.com/account_noThe customer's account numberAuth0 Action/Rule, read from the custom DB at loginWrite sess.accountNo, call the Account Attribute API and the Login Status API
https://claims.example.com/connectionThe connection used to authenticateAuth0 ActionCheck 6 in the verification table: stop tokens from another connection leaking into the flow

5.2 Why accountNo is not taken from the client

The "easy" way is to have the UI send the account number to /auth/web/login?accountNo=... or have the BFF read it from a cookie. Both are client-controlled: an attacker logs in with their own real account but changes accountNo to someone else's. If the BFF uses that value to call the Core API, the entire authorization model collapses even though authentication is perfect.

Principle: identity and the attributes used for authorization come only from a signature-verified id_token (or from a server-to-server API keyed by the sub in the token). The uid cookie (Day 1, Part 3) is only for UI display; the BFF never reads it to make authorization decisions. This rule repeats in Day 6, Part 1 with the SSO token: sub comes from the SSO Token Verify API, not from the app.

6. Common mistakes and how the spec blocks them

MistakeWhy it is dangerousMemberPortal spec
Only jwt.decode() without verify()Anyone can mint a token with a fake signatureCheck 1 is mandatory; the code uses jwtVerify
No alg allow-listalg: none / HS256 confusionStates "RS256 only" explicitly
Not checking audA token issued for another client (e.g. stepup-passkey-web) works for web login → step-up checks are bypassed, or vice versaCheck 3, aud per the client in use
Not checking iss with 2 IdPsA Keycloak token works in the Auth0 flow and vice versa; a compromised Keycloak drags Auth0 down with itCheck 2, iss per the idProvider in SessionID1
Fetching JWKS on every requestSlow callbacks, IdP rate limiting, an IdP outage takes the BFF downCache at boot, refetch by kid
Caching JWKS foreverKey rotation makes every login failRefetch on an unknown kid + cacheMaxAge
Trusting auth_time without sending max_ageWithout max_age, auth_time is OPTIONAL: it may be missing, or reflect an old SSO authenticationStep-up sends prompt=login&max_age=600; check 7 only applies when max_age is present
Taking accountNo from query/cookieTakeover of another person's accountOnly from a verified claim
Returning the verification failure reason to the userAttacker can probe: aud correct, nonce wrong...One "Login failed" screen, error codes only in logs

Review Questions

  1. In MemberPortal's BFF model, who is the Client per RFC 6749? Why not the browser?

    Show answer

    The Client is the NestJS BFF. The Client is the party "requesting access on behalf of the Resource Owner" and is registered with the Authorization Server with a client_id/client_secret. The BFF is the one calling /oauth/token, holding the client_secret, and receiving the id_token. The browser is only the User-Agent: it carries redirects and the sid cookie, holds no secret, and never sees the code_verifier or tokens. Naming the roles correctly lets the spec state clearly which party must protect what.

  2. What is the core difference between a confidential client and a public client? What extra grant type does that give MemberPortal?

    Show answer

    The difference is the ability to keep client_secret secret: a confidential client runs on a server we control (the BFF) and can keep it; a public client (SPA, mobile) cannot because its code runs on the user's device. As a confidential client, the MemberPortal BFF can use client_credentials to obtain a Management API token at startup (no user involved), and authenticates itself at /oauth/token with the client_secret. Public clients do not have client_credentials and must use PKCE.

  3. List the parameters the BFF attaches to /authorize and say which ones the BFF generates itself with a CSPRNG.

    Show answer

    response_type=code, client_id, redirect_uri, scope=openid profile, state, nonce, code_challenge, code_challenge_method=S256, connection (Auth0), optionally prompt + max_age (step-up). The three values the BFF generates with a CSPRNG on every login: state, nonce, code_verifier (from which code_challenge = BASE64URL(SHA256(code_verifier)) is computed). All three are stored in login:{id} (SessionID1) for comparison at the callback.

  4. Why does MemberPortal not use refresh_token even though it is a confidential client?

    Show answer

    Because MemberPortal's "logged-in session" is the Redis session sess:{id} with TTL SESSION_TTL, not the IdP's access_token. After the callback, the web login access_token is not used to call any Resource Server (the Internal API Gateway trusts the BFF session). With no token to renew there is no need for a refresh_token; keeping one only adds a long-lived secret to protect and another deletion branch at logout. The deliberate exception is step-up MFA (Day 7, Part 1), which keeps an access_token in stepup-mfa:{id} with TTL = expires_in because that token really does call /mfa/*.

  5. Why does the spec require that "every error branch in the callback after login:{id} has been read deletes login:{id}"?

    Show answer

    To make the login sequence single-use. If login:{id} were kept after a wrong state or wrong code, an attacker (or a client bug) could make many attempts against the same stored state/nonce/code_verifier, reducing the value of these bindings. Deleting immediately forces every attempt to start over from /auth/web/login with a fresh set of CSPRNG values. The reasonable exception: if there was no login:{id} to begin with, there is nothing to delete.

  6. What attack does PKCE block that a confidential client's client_secret does not?

    Show answer

    Authorization code injection. The attacker logs in themselves to obtain their own valid code, then injects that code into the victim's callback. Both token exchange requests go through the legitimate BFF with the same client_secret, so the secret cannot tell them apart. PKCE binds the code to the code_challenge sent by the victim's flow; the BFF uses the code_verifier from the victim's login:{id} → it does not match the attacker's challenge → Auth0 returns invalid_grant. (Combined with state, the attacker cannot even build a valid callback.)

  7. Why must code_challenge use S256 and drop the padding? What happens if the padding is kept?

    Show answer

    S256 makes code_challenge a one-way hash: anyone who intercepts /authorize (with the code_challenge) still cannot derive the code_verifier. plain sends the verifier directly, which defeats the purpose. On padding: RFC 7636 defines BASE64URL-ENCODE without =; if the BFF sends a challenge with = while the IdP recomputes it per the standard (no =), the string comparison differs → invalid_grant even though the verifier is correct. This is a common real-world bug when hand-writing base64url, which is why the MemberPortal spec spells out the padding-removal step.

  8. Why must state be checked before looking at the error parameter from the IdP?

    Show answer

    Because an error response must also prove it belongs to this browser's flow. If error were handled first, an attacker could just send a link callback?error=...&error_description=maintenance::... to force any victim to see an "Under maintenance" or "Account restricted" screen, enabling scams or state probing. Checking state first turns every invalid link into a generic "Login failed" and deletes login:{id}.

  9. How do state and nonce differ, and why does MemberPortal generate two separate values?

    Show answer

    state (OAuth 2.0) comes back in the callback's query string; the BFF compares it with login:{id}.state before exchanging the code, preventing CSRF on the callback. nonce (OIDC) comes back inside the id_token; the BFF compares it while verifying the token after exchanging the code, preventing id_token replay. Technically one value could be shared, but MemberPortal generates them separately so each value only appears in one channel: a state leaked through a URL/log does not also leak the nonce inside the token, and vice versa.

  10. Why does MemberPortal store successUrl in login:{id} instead of encoding it into state?

Show answer

Putting data into state forces the BFF to sign or encrypt state to prevent tampering; getting one step wrong opens an open redirect (the attacker crafts a state containing their own successUrl). With a Redis session in place, state only needs to be a random string, while successUrl is validated once at /auth/web/login (same BFF domain, well-formed) and stored server-side, where nobody can alter it in transit. General principle: state is a proof, not a vehicle for carrying data.

  1. The token arrives over TLS from Auth0 with a client_secret; why must the BFF still verify the signature and claims?
Show answer

TLS only proves that the packet came from the Auth0 server at that moment; it does not prove that the token is meant for this client (aud), for this session (nonce), from the same IdP that started the flow (iss, important with a Keycloak backup), and still valid (exp). Verification is also the only place where nonce and auth_time are checked. In addition, OIDC Core §3.1.3.7 states that the Client MUST validate the id_token; doing it per the standard makes the logic reusable for any channel that delivers tokens later.

  1. List MemberPortal's 7 id_token checks and say which one is "conditional" and on what condition.
Show answer

(1) Signature by kid from JWKS, alg allow-list RS256; (2) iss matches the IdP per idProvider; (3) aud contains the client_id in use; (4) exp still valid; (5) nonce matches login:{id}.nonce; (6) custom claim https://claims.example.com/connection is in the client's set of valid connections; (7) auth_time: only when the /authorize request had max_age (step-up sends prompt=login&max_age=600), requiring now - auth_time ≤ 600s. Any failed check → delete SessionID1, "Login failed", log an internal error code.

  1. Why must the BFF allow-list alg = RS256 instead of reading alg from the token header?
Show answer

Because the header is controlled by whoever sends the token. If the library trusts the alg in the header: (a) alg: none → an unsigned token is accepted; (b) algorithm confusion: the attacker changes RS256 to HS256 and signs an HMAC using the RSA public key itself (published via JWKS) as the secret; the library uses the public key to verify the HMAC → match. A fixed allow-list of RS256 (and not using jku) eliminates both. jose.jwtVerify with algorithms: ['RS256'] does exactly this.

  1. Why does MemberPortal's web login not send prompt=login/max_age while the common process still keeps the auth_time check?
Show answer

Web login dropped prompt=login because the business wants customers already logged in via SSO to another ACME app not to re-enter their password. But step-up authentication (withdrawals, changing the payee account) still needs forced re-authentication, so it still sends prompt=login&max_age=600. The common process is written by condition ("only when the request has max_age, check auth_time ≤ 600s") rather than by endpoint name, so removing prompt from web login does not affect step-up, and nothing has to be changed in two places.

  1. Why must accountNo come from the id_token rather than from the query string or the uid cookie?
Show answer

The query string and cookies are both client-controlled: an attacker logs in with their own account and then changes accountNo to the victim's; if the BFF uses that value to call the Core API, authorization collapses even though authentication is correct. The claim https://claims.example.com/account_no is put into the id_token by Auth0 from the custom DB and is protected by the signature verified in check 1, so it cannot be altered. The uid cookie is only for display; the BFF never reads it to make authorization decisions. By the same principle, Day 6, Part 1 takes sub from the SSO Token Verify API, not from the app.

Hands-on Exercises

Exercise 1: Role-play

For the following three scenarios, fill in a "Resource Owner / Client / AS / RS" table and mark whether the client is confidential or public:

  1. MemberPortal web login through the BFF.
  2. The native ACME Trade App calling Auth0 directly (assuming it does not go through the BFF).
  3. An internal cron job using portal-management to call the Auth0 Management API.

Expected output: a 3-row table, each row with all 4 roles and the client type, plus a one-line rationale.

Exercise 2: Build the flow with curl (sandbox)

Create a free Auth0 tenant or a local Keycloak (docker run quay.io/keycloak/keycloak start-dev), and register a confidential client with redirect URI http://localhost:3000/cb. Build the /authorize URL yourself with all the parameters from section 5.1 (generate state, nonce, code_verifier with node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"), open it in a browser, copy the code from the callback URL, then call /oauth/token with curl.

Expected output: a JSON response containing an id_token; decode the payload with jwt.io or node -e to see the nonce claim matching the value you generated. Record what happens when you call /oauth/token a second time with the same code.

Exercise 3: Condensed spec table

Write an Item/Required/Value table for the POST /oauth/token request in exactly the format of section 6, and list 4 error branches that can occur in leg 3 (for each branch note: retry or not, which session is deleted, which screen is shown).

Expected output: 1 table + 4 error-branch bullets, using MemberPortal's exact session/cookie names.

Exercise 4: Verify PKCE by hand

Run generatePkce() from section 2.3 and print codeVerifier and codeChallenge. Recompute the challenge with a shell command:

printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '='

Expected output: two identical strings, 43 characters, no =. Try removing the tr -d '=' step to see the difference.

Exercise 5: Reproduce login CSRF in a sandbox

Use the Keycloak/Auth0 sandbox from Day 3, Part 1. Write a small callback handler (Express/Nest) that deliberately skips the state check. Open two browsers, A (attacker) and B (victim): A logs in, stops at the callback redirect step, and copies the URL; paste the URL into B. Expected output: B is "logged in" with A's identity. Re-enable the state check (comparing against the value in B's session) and record the result.

Exercise 6: Binding table for a new flow

Suppose a new channel "Desktop app WebView login" is added (to be used in Day 7, Part 3). Fill in a table: value (code_verifier, state, nonce), which endpoint generates it, which Redis key stores it, which step checks it, and the action on mismatch. Expected output: a 3-row × 5-column table using MemberPortal session/cookie names; point out 1 difference (if any) from the Web channel.

Exercise 7: Verify a real token with jose

Use the id_token from Exercise 2 of Day 3, Part 1. Write a Node script using createRemoteJWKSet + jwtVerify with the correct issuer, audience, algorithms: ['RS256']. Then in turn: use a wrong audience, change 1 character in the payload (re-encode), wait for the token to expire. Expected output: 3 different error types from jose (JWTClaimValidationFailed, JWSSignatureVerificationFailed, JWTExpired); record the error names and which of the 7 checks each corresponds to.

Exercise 8: Simulate key rotation

With a local Keycloak: create an additional key in the realm (Realm settings → Keys → Providers), give it a higher priority, and log in again to get a token with the new kid. Re-run the script from Exercise 1 with a createRemoteJWKSet created before the key was added. Expected output: verification still succeeds (jose refetches JWKS on an unknown kid); record the number of requests to the JWKS endpoint from the Keycloak log or a proxy.

Exercise 9: Write the "id_token validation" section for a spec

Rewrite the 7-check table in spec format (columns: Check / What is checked / Where the expected value comes from / Action on failure), adding a "Log error code" column of your own. Then write 3 lines for the case of adding a third IdP: which columns change and which do not. Expected output: a 7-row × 5-column table + a 3-line analysis.

References


Next lesson →