devHọc Dev

Week 1 - Day 4: client_credentials, IdP error handling, RP-initiated logout and sequence diagrams

Week 1 – Day 4

This lesson combines 3 topics: client_credentials & Management API — token at startup, refresh, retry, Handling IdP errors & RP-initiated logout, Drawing the Web login sequence diagram with Mermaid.

Learning Objectives

  • Understand what the client_credentials grant is, how it differs from authorization_code, and when the BFF needs it
  • Distinguish Auth0's Authentication API from its Management API, and the corresponding scopes/permissions
  • Design the BFF boot process: obtain a Management API token, load JWKS, check configuration; decide "what happens if boot fails"
  • Write a correct policy for refreshing when < 5 minutes remain and retrying at most 2 times on 5xx/timeout
  • Be able to answer: why a token obtained at boot is enough to call /api/v2/users/* instead of the user's token
  • Read the error response of /authorize (error, error_description) and know where in the IdP it comes from
  • Build MemberPortal's IdP error → screen mapping table and explain each row
  • Weigh user enumeration: when to separate error messages and when to merge them
  • Understand the IdP-side redirect URI allow-list and why one client can have several callback URLs
  • Design a three-step RP-initiated logout: logout → logout-callback → logout-complete, with Auth0 /v2/logout and Keycloak end_session
  • Draw the complete sequence diagram of MemberPortal's Web login from clicking "Sign in" to landing on successUrl
  • Mark on the diagram where state, nonce, code_verifier, SessionID1 and SessionID2 are created and read
  • Use alt/else to represent the main error branches instead of drawing many separate diagrams
  • Check Mermaid syntax with mermaid-cli before putting it into documentation
  • Match the diagram 1-to-1 against the spec's "Processing details", and build an RFC ↔ step table

Part 1: client_credentials & Management API — token at startup, refresh, retry

1. Some BFF work happens with no user logged in

The Authorization Code flow (Day 3, Part 1) is always tied to a specific user sitting in front of the browser. But MemberPortal has tasks such as:

TaskWhenIs a user logged in?
Read the user's user_metadata (e.g. passkey_fallback_url, passkey-enrolled flag)In the step-up callback (Day 7, Part 1)Yes, but the user token has no Management API permission
Update user metadata after MFA enrollmentAfter the MFA stepSame as above
Load the JWKS of Auth0 and KeycloakAt startupNo
Check that the IdP configuration is still correct (client exists, callback URL)At startup / health checkNo

For these tasks, OAuth 2.0 has the client_credentials grant (RFC 6749 §4.4): the client authenticates itself with client_id + client_secret and receives an access_token representing the client itself, not any user. Because it needs client_secret, only a confidential client (Day 3, Part 1) can use it. The BFF is a confidential client, so it can.

authorization_codeclient_credentials┌─────────────────────────────────────┐┌─────────────────────────────────────┐│Whoasks:BFFonbehalfoftheUSER││Whoasks:BFFforITSELF││Needs:userinteractionviabrowser││Needs:client_id+client_secret││Tokensays:"userXallowsclient││Tokensays:"clientYisallowedto││Ytodosomething"││doX"(pergrantedpermissions)││Hasid_token,sub=user││Noid_token,││││sub=<client_id>@clients││Liveswiththeusersession││Livesbyexpires_in,shared│└─────────────────────────────────────┘└─────────────────────────────────────┘

2. Authentication API vs Management API (Auth0)

Auth0 splits its API into two surfaces, and the MemberPortal spec states clearly which client calls what:

Authentication APIManagement API
Base URLhttps://login.example.com/https://login.example.com/api/v2/
What it does/authorize, /oauth/token, /v2/logout, /userinfo, /mfa/*, /.well-known/jwks.jsonCRUD users, clients, connections, read/write user_metadata, manage authenticators
Who calls itBrowser (redirect) and BFF (token exchange)BFF only, server-to-server
Token requiredNone (or the user token for /userinfo, /mfa/*)Access_token with aud = https://login.example.com/api/v2/ and scopes such as read:users, update:users
MemberPortal clientportal-web, the stepup-* clientsportal-management
Grantauthorization_code, mfaclient_credentials

Three questions that the spec's IdP client table (Day 7, Part 3 teaches how to write it) must answer for portal-management:

  1. Which permissions are granted on the Management API? MemberPortal: read:users, update:users, read:users_app_metadata, update:users_app_metadata. No delete:users, no create:clients. The principle of least privilege.
  2. Is there a callback URL? No. client_credentials does not redirect. The client table puts "—" in the callback column so readers do not wonder.
  3. Who holds the secret? The BFF, via the env IDP_MGMT_CLIENT_SECRET (separate from IDP_CLIENT_SECRET of portal-web) (the value lives in the infrastructure's SSM/secret manager, never in docs or the repository).

3. The BFF boot process

The MemberPortal spec has a dedicated "Startup processing" section placed before every endpoint, because many endpoints assume that boot succeeded. This is what new spec writers often forget: they describe runtime but not the initial state.

dockerstart/podstart│├─1.Read&validateenv:STAGE,IDP_CLIENT_ID,IDP_CLIENT_SECRET,│IDP_MGMT_CLIENT_ID,IDP_MGMT_CLIENT_SECRET,BFF_DOMAIN,│SESSION_*_TTL,ALT_IDP_ENABLED,PASSKEY_ENABLED...│requiredvariablemissing→logFATAL,exit1(nohalf-workingservice)│├─2.ConnecttoRedis(ping)──fail→exit1│├─3.ObtaintheManagementAPItoken:│POST/oauth/tokengrant_type=client_credentials│client_id=<portal-management>,client_secret=<...>,│audience=https://login.example.com/api/v2/│retry≤2timeson5xx/timeout──stillfails→exit1│store{access_token,expiresAt}inmemory(NOTRedis,NOTlogged)│├─4.LoadtheAuth0JWKS;ifALT_IDP_ENABLED=truealsoloadtheKeycloakJWKS│retry≤2times──fail→exit1│├─5.Startthetokenrefreshscheduler(section4)andtheAuthHealthcache(Day6,Part3)│└─6.Opentheport,readinessprobereturns200

3.1 Design decision: "what if boot fails"

There are two schools of thought:

  • Fail-fast: any failing step exits. Kubernetes/ECS will restart it, and the pod is never "half alive". MemberPortal chooses this for steps 1–4.
  • Degraded start: start even without the Management API token, so web login still works (web login does not need the Management API), and only step-up is affected.

MemberPortal chooses fail-fast because: (a) a client_credentials failure usually means a wrong secret configuration, which should be detected right at deploy time rather than when the first customer withdraws money; (b) the readiness probe honestly reflects "ready to fully serve". The spec records the decision and the reason, so later readers do not "improve" it into a degraded start and introduce confusing bugs.

3.2 Where the token lives

The Management API token lives only in the memory of the BFF process. It is not written to Redis (Redis is the session store, and more people have read access to it), not logged, and not returned by any endpoint. Each BFF instance obtains its own token; Auth0 allows multiple concurrent tokens for the same client. The cost is one /oauth/token request per instance every ~24h, negligible compared with the risk of sharing the token through a common store.

4. Refresh when < 5 minutes remain

client_credentials has no refresh_token; when it expires you request a new token with the same grant. The question is when to request it.

StrategyProblem
Request when an API call returns 401The first customer request after the token expires is slow or fails; you have to write retry-on-401 at every place that calls the Management API
Request before every requestWasteful, easily rate-limited by Auth0
Request a buffer period before expiryMemberPortal's choice: refresh when < 5 minutes remain
interface CachedToken { accessToken: string; expiresAt: number } // epoch ms

const REFRESH_MARGIN_MS = 5 * 60_000;
let cached: CachedToken | null = null;
let inflight: Promise<CachedToken> | null = null;

export async function getManagementToken(): Promise<string> {
  const now = Date.now();
  if (cached && cached.expiresAt - now > REFRESH_MARGIN_MS) return cached.accessToken;

  // Collapse concurrent callers into a single request (do not request 50 tokens at once)
  if (!inflight) {
    inflight = fetchWithRetry(() => requestClientCredentialsToken(), 2)
      .then((t) => (cached = t))
      .finally(() => (inflight = null));
  }
  return (await inflight).accessToken;
}

async function requestClientCredentialsToken(): Promise<CachedToken> {
  const res = await fetch('https://login.example.com/oauth/token', {
    method: 'POST',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: process.env.IDP_MGMT_CLIENT_ID!,          // client portal-management
      client_secret: process.env.IDP_MGMT_CLIENT_SECRET!,  // value from the secret manager
      audience: 'https://login.example.com/api/v2/',
    }),
    signal: AbortSignal.timeout(5_000),
  });
  if (!res.ok) throw new HttpError(res.status);
  const body = await res.json() as { access_token: string; expires_in: number };
  return { accessToken: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 };
}

Why 5 minutes? Wide enough for one token request (including 2 retries with a 5s timeout) to complete before the old token expires, narrow enough not to waste most of the token's lifetime. The number must be written in the spec with its reason, not left in code as a magic number.

Spec note: besides the lazy refresh above, MemberPortal also has a scheduler that runs periodically (e.g. every minute) and calls getManagementToken() to keep the token "warm", avoiding the case where there are no requests for a long time and the first request then has to wait.

5. Retry at most 2 times on 5xx/timeout

MemberPortal's retry policy applies uniformly to every server-to-server request to the IdP: /oauth/token (both authorization_code and client_credentials), JWKS, Management API.

ScenarioRetry?Reason
Timeout (no response received)Yes, ≤ 2 timesCould be a transient network issue
500, 502, 503, 504Yes, ≤ 2 timesTransient IdP-side error
429 Too Many RequestsNo in the basic policy; log a warningRetrying immediately makes it worse; needs a longer backoff or investigation
400, 401, 403NoWrong configuration / wrong secret / wrong grant; retrying is useless and hides the real error
invalid_grant when exchanging codeNoCode expired / already used / wrong PKCE (Day 3, Part 2); the flow must start over
async function fetchWithRetry<T>(fn: () => Promise<T>, maxRetries: number): Promise<T> {
  let attempt = 0;
  for (;;) {
    try {
      return await fn();
    } catch (e) {
      const retryable = e instanceof HttpError ? e.status >= 500 : isTimeout(e);
      if (!retryable || attempt >= maxRetries) throw e;
      attempt += 1;
      await sleep(200 * attempt); // simple linear backoff; enough for 2 attempts
    }
  }
}

"At most 2 retries" means at most 3 requests in total. The spec must state this explicitly because "retry 2 times" is understood differently by developers and testers. MemberPortal writes: "retry at most 2 times (3 calls in total)".

Applied to the web login callback: if /oauth/token fails all 3 times, the BFF deletes login:{id} and goes to "Login failed". There is no "wait for the IdP to recover and continue" branch because the user is waiting for a redirect; at most ~15s (3 × 5s timeout) is an acceptable limit.

6. Why a token obtained at boot is enough to call /api/v2/users/* instead of the user's token

This question comes up in every MemberPortal spec review, because intuition says "to read user X's data you need user X's token".

The answer, in terms of the OAuth model:

  • User X's token (from authorization_code) says "user X allows client portal-web to do something on X's behalf". Auth0 does not issue Management API scopes to this kind of token through normal Universal Login; and by design, an end user should not have read:users across the whole tenant.
  • The client_credentials token of portal-management says "client portal-management has been granted the permissions read:users, update:users, read:users_app_metadata, update:users_app_metadata by the tenant admin". It is a system permission, independent of who is logged in. The BFF uses it to call GET /api/v2/users/{sub} with sub taken from the verified id_token (Day 3, Part 3).
Businessquestion:"whatisthisuser'spasskey_fallback_url?"sub(fromverifiedid_token)──┐├──▶GET/api/v2/users/{sub}Managementtoken(boot)──┘Authorization:Bearer<managementtoken>─▶{user_metadata:{passkey_fallback_url:...}}

Two accompanying security conditions that the spec states explicitly:

  1. sub must come from a verified token or from sess:{id} (which was written from a verified token). Never from a client-controlled query/cookie. Otherwise the Management token becomes a tool for reading the metadata of any user.
  2. Minimum permissions. portal-management has no delete:users and no permissions on clients/connections. If the BFF is compromised, the damage is limited to reading/modifying metadata.

This is a textbook example of the trusted subsystem model: the BFF is trusted to access resources with a system identity, and the BFF is responsible for using it only within the context of an authenticated user.

7. Writing it into the spec

A condensed template for the "Startup processing" section and the client table:

Startup processing

  1. Validate env (required list: ...). Missing → FATAL, stop.
  2. Connect to Redis. Fail → FATAL, stop.
  3. Obtain the Management API token (client portal-management, grant client_credentials, audience Management API). Retry at most 2 times (3 in total) on 5xx/timeout. Fail → FATAL, stop. Token stored in memory; refreshed when less than 5 minutes remain.
  4. Load the Auth0 JWKS; if ALT_IDP_ENABLED=true, load the Keycloak JWKS. Retry as in step 3. Fail → FATAL, stop.
  5. Readiness OK.

Client table (excerpt)

ClientGrantCallbackManagement API permissionsPurposeDesign rationale
portal-managementclient_credentials—read:users, update:users, read:users_app_metadata, update:users_app_metadataBFF reads/writes user metadata for step-up/MFANeeds a system permission outside the user context; least privilege, no delete

Part 2: Handling IdP errors & RP-initiated logout

1. How IdP errors come back

In Day 3, Part 2, the callback checks state first and only then looks at error. Today we talk about that error parameter itself. RFC 6749 §4.1.2.1 specifies that when the Authorization Server cannot or will not issue a code, it redirects back to redirect_uri with:

ParameterRequiredMeaning
errorYesStandard error code: invalid_request, unauthorized_client, access_denied, unsupported_response_type, invalid_scope, server_error, temporarily_unavailable
error_descriptionNoHuman-readable string, freely filled in by the IdP
error_uriNoDocumentation link

| state | Yes if present in the request | Must match (Day 3, Part 2) |

Note: Auth0 also returns error=unauthorized (for example when the user is blocked). This code is not in RFC 6749; it is Auth0-specific, so the spec must list it explicitly rather than assume the IdP only uses the standard set of codes.

Key point for spec writers: error has a standard set of values, but error_description does not. Auth0 fills error_description with the message from a custom DB script or an Action; Keycloak fills it differently. If the spec has to branch on error_description, the spec must state the exact string and its origin (who writes that string on the IdP side), because this is an implicit contract between the two systems.

Auth0UniversalLogin│├─CustomDBscript"login":userdoesnotexist/wrongpassword│→Auth0showstheerrorinplace,doesNOTredirecttotheBFF(userretries)│├─CustomDBscript:returncallback(newError('maintenance::core-db'))│→error=access_denied&error_description=maintenance::core-db│├─UserblockedinAuth0(brute-forceprotection/adminblock)│→error=unauthorized&error_description=userisblocked(Auth0string)│├─Connectiondisabledforthisclient│→error=invalid_request&error_description=connectionisnotenabled(Auth0string)│├─"post-login"Actionrejectsbyaccounttype×client_id(Day6,Part2)│→api.access.deny('not-eligible')│→error=access_denied&error_description=not-eligible│└─Userclicks"Cancel"orIdPtimeout→error=access_denied(Auth0)/error=access_deniedorlogin_required(Keycloak)

First lesson: not every error comes back to the BFF. A wrong password stays on the IdP page. The MemberPortal spec states this explicitly so testers do not look for a "wrong password" branch in the callback.

2. MemberPortal's IdP error → screen mapping table

Callback /auth/web/login-callback, after state matches and error is present:

#Condition (matched in order)Root cause on the IdP sideWhat to deleteScreen / actionWhy it is separate
1error_description == "user is blocked"Account blocked by Auth0 (brute-force, admin)login:{id}"Your account is restricted from logging in" with instructions to contact supportThe customer needs to know they must do something else (call the hotline) instead of retrying
2error_description == "connection is not enabled" or error_description starts with maintenance::Operations disabled the connection or the custom DB reports maintenancelogin:{id}"Login is under maintenance" (HTTP 503 for an API, static page for a redirect)The customer should come back later; not the customer's fault
3error == "access_denied" (any other error_description)IdP rejects by account type (Day 6, Part 2), user cancels, Action denylogin:{id}"Login failed", redirect to failureUrl if presentMerged so the specific reason is not revealed
4Any other error (server_error, temporarily_unavailable, invalid_request not covered by row 2...)IdP or configuration errorlogin:{id}"Login failed" + log the error code at ERROR level for operations to investigateNo different action for the customer

Four rules to take away:

  1. Matching order matters. Row 2's maintenance:: comes with error=access_denied; if you check error == access_denied first, every maintenance error becomes "Login failed". The spec says "match in order from top to bottom".
  2. Every branch deletes login:{id}. The same use-once rule as Day 3, Part 2.
  3. The error_description string is a contract. The spec records the source: "user is blocked" and "connection is not enabled" are fixed strings emitted by Auth0; maintenance:: is a prefix agreed between the IdP operations team and the BFF, recorded in a document shared by both sides. Changing the string on the IdP side without changing the BFF spec is a real incident that has happened in many projects.
  4. Keycloak (the backup IdP) has different strings. When idProvider = keycloak, the mapping table has its own version (Day 6, Part 3); the spec points to a per-IdP mapping file instead of mixing the two tables.

3. Weighing user enumeration

Splitting "Account restricted" into its own screen means revealing to whoever is in front of the screen that this account exists and is locked. Is that an enumeration vulnerability?

MemberPortal's analysis (which should be in the spec as "design rationale"):

FactorAssessment
Who sees the messageSomeone who has entered the correct password (Auth0 only returns user is blocked after the authentication step, or when blocking due to brute-force on that exact user) or the account owner. An attacker without the password only sees the wrong-password error on the IdP page
Benefit to the customerVery high: they know to call the hotline instead of uselessly changing the password, reducing support tickets
RiskLow, because to reach this branch the attacker must have the password; in that case the block is protecting the account exactly as designed
ConclusionSeparate it, intentionally, and record it in the spec

Conversely, row 3 merges every access_denied because "account type not eligible" reveals that the account exists before the password is known in some configurations. Principle: detailed messages only when the recipient has proven their identity; otherwise use a generic message.

4. Redirect URI allow-list and one client with several callbacks

4.1 Why the IdP has an allow-list

redirect_uri is where the IdP sends the code. If the IdP accepted any redirect_uri the client sent, an attacker could craft a link /authorize?...&redirect_uri=https://evil.example/cb and send it to a victim: the victim logs in to the real Auth0, and the code flies to the attacker. RFC 6749 §3.1.2.2 requires the client to register in advance and the IdP to match exactly (no wildcard, no prefix matching). Auth0 calls it "Allowed Callback URLs", Keycloak calls it "Valid redirect URIs".

Practical consequences for MemberPortal:

  • The redirect_uri in /authorize and in /oauth/token must be byte-for-byte identical to each other and to the Auth0 configuration, including https, with no extra trailing slash.
  • Each environment (dev/stg/prod) has a different BFF_DOMAIN → either one Auth0 tenant/client per environment, or one client listing several URLs. MemberPortal chooses one tenant per environment, avoiding dev URLs in the prod client.

4.2 One client, several callbacks

MemberPortal's IdP client table has the client stepup-password-web with two login callbacks:

  • https://{BFF_DOMAIN}/auth/stepup/callback — completes step-up for the cash-out / withdrawal-account context, creating stepup:{id} with TTL 600s.
  • https://{BFF_DOMAIN}/auth/stepup/mfa-callback — when step-up serves MFA management (enroll/change authenticator), the BFF needs to receive it at a different endpoint to create stepup-mfa:{id} with TTL = expires_in instead of stepup:{id} 600s (Day 7, Part 1).
clientportal-webAllowedCallbackURLs:https://portal.example.com/auth/web/login-callbackAllowedLogoutURLs:https://portal.example.com/auth/web/logout-callback◀──logoutusesclient_id=portal-web(section5)clientstepup-password-webAllowedCallbackURLs:https://portal.example.com/auth/stepup/callback◀──context=cash-out/withdrawal-accounthttps://portal.example.com/auth/stepup/mfa-callback◀──context=security-setting(MFA)

The two alternatives are both worse: (a) a single callback that branches on context in the session, which bloats the callback and makes the two kinds of sub-session easy to confuse; (b) two separate clients, which increases the number of secrets to manage. The spec records the choice (one purpose per callback, same client) in the "design rationale" column. What to remember in review: every URL in the allow-list is an entry point; it must have a real endpoint, check state, and be listed in the spec. A URL kept "just in case" without an endpoint is an open-redirect vulnerability waiting to happen.

5. RP-initiated logout

5.1 Logout has two halves

Day 2, Part 3 covered logout on the BFF side: delete sess:{id}, invalidate the sid/xsrf/uid cookies. But the IdP still keeps its own SSO session. If you only log out of the BFF, a customer who clicks "Sign in" again is let straight in by Auth0 without a password prompt (because web login does not send prompt=login, Day 3, Part 3). On a shared machine, that is an incident.

OIDC RP-Initiated Logout 1.0 defines how a Relying Party (the BFF) asks the IdP to end the SSO session and return.

5.2 MemberPortal's three endpoints

sequenceDiagram
    participant B as Browser
    participant BFF
    participant A as Auth0
    B->>BFF: GET /auth/web/logout<br/>(cookie sid, top-level GET)
    Note over BFF: read sess (no XSRF check)<br/>delete sess:{id}<br/>Set-Cookie sid/xsrf/uid = #59; Max-Age=0
    BFF-->>B: 302 https://login.example.com/v2/logout?client_id=<portal-web><br/>&returnTo=https://portal.example.com/auth/web/logout-callback
    B->>A: GET /v2/logout (following the redirect)
    Note over A: Auth0 deletes the SSO session
    A-->>B: 302 https://portal.example.com/auth/web/logout-callback
    B->>BFF: GET /auth/web/logout-callback
    Note over BFF: clear cookies again (idempotent)
    BFF-->>B: 302 /auth/web/logout-complete
    B->>BFF: GET /auth/web/logout-complete
    Note over BFF: "Signed out" page + sign-in button
EndpointWhat it doesWhy it is separate
GET /auth/web/logoutReads the session (does not require X-XSRF-TOKEN, see design rationale), deletes sess:{id} first, clears cookies, redirects to IdP logoutDeleting the BFF session first means the BFF side is safe even if IdP logout fails
GET /auth/web/logout-callbackWhere the IdP returns (listed in Allowed Logout URLs); clears cookies again; redirects to completeA technical URL with no content; separated so the UI does not depend on the URL name the IdP needs
GET /auth/web/logout-completePage shown to the customerCan be a static, cacheable page with no logic

Design rationale (consistent with Day 2, Part 3): GET /auth/web/logout is a top-level navigation (the user clicks a link/button); the browser cannot attach a custom header, so it is impossible to require X-XSRF-TOKEN as with /api/s/*. The remaining risk is "logout CSRF" (someone forces the victim to log out via a link/image); the only consequence is being logged out, with no data leaked, so MemberPortal accepts it intentionally and records it in the spec.

5.3 Auth0 /v2/logout vs Keycloak end_session

Auth0Keycloak (standard OIDC)
EndpointGET /v2/logoutGET /realms/{realm}/protocol/openid-connect/logout
Return parameterreturnTo (must be in the client's or tenant's Allowed Logout URLs)post_logout_redirect_uri (must be in Valid post logout redirect URIs)
Client identificationclient_idclient_id or id_token_hint (old id_token JWT)
Logout from an external (federated) IdPfederatedDepends on the configured identity provider
For MemberPortalUse client_id + returnToUse client_id + post_logout_redirect_uri; do not use id_token_hint because the BFF does not store the id_token after login (Day 3, Part 1)

Because idProvider is stored in sess:{id} (copied from SessionID1 at callback time), /auth/web/logout knows which IdP to redirect to. This is the second reason idProvider must live on in SessionID2 and not just in SessionID1. Sessions that do not go through an IdP (channel App from an SSO token, Operator, mock:) have no idProvider; for those sessions logout only deletes the session + cookies and then 302s straight to /auth/web/logout-complete, skipping the IdP logout step. The spec must document this branch, otherwise developers will redirect to undefined.

5.4 Logout error branches

ScenarioHandling
No sess:{id} (TTL already expired)Still clear cookies, still redirect to IdP logout: when a user clicks logout they must be able to get out; do not show 401
Someone forces the victim to log out via a link/image (logout CSRF)Accepted intentionally: a top-level navigation cannot attach X-XSRF-TOKEN; the only consequence is being logged out (Day 2, Part 3). If the business does not accept this, switch to POST /auth/web/logout called via fetch + XSRF, returning a URL for the UI to navigate to
IdP logout returns an error or does not come backThe BFF side is already clean; the customer may see the IdP's error page. Accepted, documented in the spec
returnTo is not in the allow-listAuth0 shows an error and does not redirect. This is a configuration error and must be caught in the stg environment
Native app WebView (channel App)BFF logout does not delete APP_SSO_TOKEN (Day 2, Part 3); the app manages its own session

6. Writing it into the spec

Excerpt from /auth/web/login-callback — "When the error parameter is present"

  • Delete login:{sid}.
  • Match in order:
    1. error_description = user is blocked → go to the "Your account is restricted from logging in" screen.
    2. error_description = connection is not enabled, or starts with maintenance:: → go to the "Login is under maintenance" screen.
    3. Otherwise → go to "Login failed" (failureUrl if present, the login page by default).
  • Log: bffErrCode, error, error_description (do not log state, do not log cookies).
  • Design rationale: strings 1 and 2 are fixed strings emitted by Auth0; the maintenance:: prefix is agreed with IdP operations (link to the shared document). Screen 1 is separated intentionally; see the enumeration analysis.

Excerpt from /auth/web/logout

LocationItemRequiredRule
cookiesidNoPresent → delete sess:{sid}; absent → skip
headerX-XSRF-TOKENNoNot checked: a top-level navigation cannot attach a custom header; logout CSRF accepted intentionally (Day 2, Part 3)

Processing details: delete session → clear cookies (sid, xsrf, uid, sid_stepup; do not touch APP_SSO_TOKEN) → if sess.idProvider is empty (App/Operator/mock session, no IdP session) → 302 straight to /auth/web/logout-complete; otherwise → 302 to the logout endpoint of sess.idProvider (Auth0: /v2/logout?client_id&returnTo; Keycloak: .../logout?client_id&post_logout_redirect_uri) with the return URL /auth/web/logout-callback.

Part 3: Drawing the Web login sequence diagram with Mermaid

1. What diagrams are for in a spec

The MemberPortal spec has a separate file containing the sequence diagrams, and every endpoint links to its own diagram. Diagrams do not replace the bullet-style "Processing details" (Day 7, Part 3); they serve three other purposes:

ReaderUses the diagram to
New developerGrasp the big picture in 5 minutes before reading 3 pages of bullets
TesterCount the requests to observe in DevTools, know where cookies are set
Security reviewerSee which value is generated where, travels through where, and compared where (exactly the three bindings from Day 3, Part 2)

The 1-to-1 match principle: every arrow in the diagram corresponds to exactly one step in "Processing details" and vice versa. When you change the spec you must change both; a PR that changes only one side is a signal to ask again.

Why Mermaid: it is text, diffable in PRs, rendered out of the box on GitHub/GitLab and many wikis, and mermaid-cli can check its syntax in CI.

2. The Mermaid sequenceDiagram syntax needed for a login flow

sequenceDiagram
    autonumber                          %% number the arrows, handy for matching bullets
    participant B as Browser            %% short alias, long display name
    participant F as BFF
    participant R as Redis
    participant I as IdP (Auth0)

    B->>F: GET /auth/web/login          %% solid arrow = request
    F-->>B: 302 Location: /authorize    %% dashed arrow = response
    Note over F: generate state, nonce  %% note over 1 participant
    Note over B,F: cookie login_sid     %% note spanning 2 participants
    alt state matches                   %% branch
        F->>I: POST /oauth/token
    else state wrong
        F->>R: DEL login:{sid1}
    end

A few conventions MemberPortal applies to keep diagrams readable:

  • autonumber is always on: the number on an arrow is the reference number used in the bullets ("step 7 in the diagram"). Note that Mermaid only numbers arrows, not Notes; [CREATE]/[READ] markers written in a Note are referenced as "Note after step N".
  • Redis is its own participant, so every session write/read/delete is visible. This is where reviewers look the most.
  • Value names are used exactly as in the spec: login:{sid1}, sess:{sid2}; no different abbreviations between the diagram and the bullets.
  • Do not cram secondary error branches (token retry, JWKS refetch) into the main diagram; write a Note "retry ≤ 2, see Day 4, Part 1" or split out a sub-diagram.
  • Do not draw token contents; the diagram is an internally public document, and sample values are easily copied as "real values".

3. The complete Web login diagram

Below is MemberPortal's standard diagram for /auth/web/login → /auth/web/login-callback, including the success branch and the main error branches. The [CREATE]/[READ]/[DELETE] annotations mark the lifecycle of the binding values.

sequenceDiagram
    autonumber
    participant U as Customer
    participant B as Browser
    participant F as BFF (NestJS)
    participant R as Redis
    participant I as IdP (Auth0)
    participant C as Core API (Account Attribute / Login Status)

    U->>B: Click "Sign in"
    B->>F: GET /auth/web/login?successUrl=...
    Note over F: Validate successUrl (same origin as BFF, well-formed)<br/>Determine idProvider (Auth Health, Day 6, Part 3)
    Note over F: [CREATE] state, nonce, code_verifier (CSPRNG)<br/>code_challenge = BASE64URL(SHA256(code_verifier))
    F->>R: SET login:{sid1} {state, nonce, codeVerifier, successUrl, idProvider, channel=Web} TTL=SESSION_LOGIN_TTL
    Note over R: [CREATE] SessionID1
    F-->>B: 302 Location: {IdP}/authorize?response_type=code&client_id&redirect_uri<br/>&scope=openid profile&state&nonce&code_challenge&code_challenge_method=S256
    Note over B,F: Set-Cookie login_sid=sid1 (Secure, HttpOnly, SameSite=Lax)

    B->>I: GET /authorize?...
    I-->>U: Universal Login (enter password / passkey)
    U->>I: Authenticate
    Note over I: Custom DB + Action: check account type × client_id (Day 6, Part 2)

    alt Authentication OK and eligible
        I-->>B: 302 Location: {BFF}/auth/web/login-callback?code&state
    else IdP rejects
        I-->>B: 302 Location: {BFF}/auth/web/login-callback?error&error_description&state
    end

    B->>F: GET /auth/web/login-callback?... (Cookie login_sid=sid1)
    F->>R: GET login:{sid1}
    Note over F: [READ] SessionID1

    alt No login:{sid1} (TTL expired / no cookie)
        F-->>B: 302 "Login failed"
    else state ≠ login:{sid1}.state
        Note over F: [READ] state
        F->>R: DEL login:{sid1}
        F-->>B: 302 "Login failed"
    else error parameter present
        F->>R: DEL login:{sid1}
        F-->>B: 302 screen per mapping (restricted / maintenance / failed) (Day 4, Part 2)
    else code missing
        F->>R: DEL login:{sid1}
        F-->>B: 302 "Login failed"
    else code present, state matches
        Note over F: [READ] code_verifier from login:{sid1}
        F->>I: POST /oauth/token (form) grant_type=authorization_code<br/>code, redirect_uri, client_id, client_secret, code_verifier
        Note over F,I: retry ≤ 2 times on 5xx/timeout (3 in total), Day 4, Part 1
        alt Token request fails (4xx / retries exhausted)
            F->>R: DEL login:{sid1}
            F-->>B: 302 "Login failed"
        else 200 {id_token, access_token}
            I-->>F: {id_token, access_token, expires_in}
            Note over F: Verify id_token, 7 items (Day 3, Part 3):<br/>signature (JWKS/kid), iss, aud, exp,<br/>[READ] nonce == login:{sid1}.nonce,<br/>connection claim, auth_time (only when max_age was sent)
            alt Verify fails
                F->>R: DEL login:{sid1}
                F-->>B: 302 "Login failed"
            else Verify OK
                Note over F: accountNo, sub taken from id_token claims
                F->>C: Account Attribute API (accountNo)
                C-->>F: accountType
                alt Not an online trading account
                    F->>R: DEL login:{sid1}
                    F-->>B: 302 "Login failed"
                else Eligible
                    F->>C: Login Status API (accountNo)
                    C-->>F: {isLoginAllowed, needsTradingInfoEntry}
                    alt API fails or isLoginAllowed=false
                        F->>R: DEL login:{sid1}
                        F-->>B: 302 "Login failed"
                    else isLoginAllowed=true
                        Note over F: [CREATE] sid2 (CSPRNG, NOT reusing sid1), xsrfToken (CSPRNG)
                        F->>R: DEL login:{sid1}
                        Note over R: [DELETE] SessionID1
                        F->>R: SET sess:{sid2} {accountNo, sub, xsrfToken, channel=Web, idProvider, usedPasskey} TTL=SESSION_TTL
                        Note over R: [CREATE] SessionID2
                        opt needsTradingInfoEntry=false
                            F-)C: Login History API (usedPasskey) — best effort, errors ignored
                        end
                        F-->>B: 302 Location: successUrl
                        Note over B,F: Set-Cookie sid=sid2 (HttpOnly), xsrf, uid=sub
                    end
                end
            end
        end
    end

Read the diagram along the three "threads" from Day 3, Part 2:

  • state: [CREATE] Note after step 2 → stored in Redis at step 3 → out to the IdP at steps 4–5 → comes back at step 8 (or 9 on error) → [READ] compared in the second else branch (steps 13–14 if wrong).
  • nonce: [CREATE] Note after step 2 → out to the IdP at steps 4–5 → inside the id_token returned at step 22 → [READ] during verification (Note after step 22).
  • code_verifier: [CREATE] Note after step 2 → does not go to the IdP (only code_challenge goes out at steps 4–5) → [READ] when POSTing /oauth/token (step 19).

And the two sessions: login:{sid1} lives from step 3 until the final DEL in the success branch (step 33) or the DEL in any error branch; sess:{sid2} only appears at step 34, after all checks pass. If you find a path from step 10 (callback reaches the BFF) to successUrl (step 36) that does not go through DEL login:{sid1}, that is a spec bug. How to count: only arrows are numbered, including arrows in alt/else branches that are not taken.

4. Checking syntax with mermaid-cli

A diagram as long as the one above makes it very easy to misplace an end or an else; GitHub only reports "Unable to render" without pointing to the line. MemberPortal runs a check in CI for every PR that changes documentation:

# Install locally (no global install needed)
npx -y @mermaid-js/mermaid-cli -i docs/sequence-web-login.mmd -o /tmp/web-login.svg

# For a markdown file with several ```mermaid fences: extract and render each block
npx -y @mermaid-js/mermaid-cli -i docs/sequence.md -o /tmp/sequence.md
#   → mmdc replaces each mermaid block with an image and creates sequence-1.svg, sequence-2.svg ...
#   → exit code ≠ 0 if any block has an error, with a message pointing to the error line

A minimal CI example (GitHub Actions):

- name: Validate mermaid diagrams
  run: |
    set -e
    for f in $(git ls-files 'docs/**/*.md' | xargs grep -l '```mermaid' || true); do
      npx -y @mermaid-js/mermaid-cli -i "$f" -o "/tmp/$(basename "$f")" >/dev/null
    done

Note: mermaid-cli needs headless Chromium (puppeteer downloads it on install). In CI you can use the image ghcr.io/mermaid-js/mermaid-cli/mermaid-cli to skip the download step.

Common errors and how to fix them:

MessageCauseFix
Parse error ... Expecting 'end'Missing end for alt/opt/loopCount the alt/opt/loop and end keywords; consistent indentation helps spot it
Expecting 'NEWLINE' ... got 'TXT'Unescaped ; or # in a messageReplace with a word or use #59;
Text overflowsMessage too longBreak it with <br/>
Arrow to an undeclared participantMistyped aliasDeclare every participant at the top

5. 1-to-1 matching with "Processing details" and with the RFCs

5.1 Step ↔ spec bullet matching table

How MemberPortal keeps them in sync: each bullet in the spec records the diagram step number in square brackets.

Diagram step (autonumber)Bullet in /auth/web/login or login-callback
2 (+ Note)login: receive successUrl, validate same origin, determine idProvider
3 (+ Note)login: generate state/nonce/code_verifier, store login:{sid1} with TTL SESSION_LOGIN_TTL
4 (+ Note)login: 302 to /authorize with the parameters from table 5.1 of Day 3, Part 1; Set-Cookie login_sid
5–7(IdP side) /authorize, Universal Login, authentication — no BFF bullet, just a note
8 / 9IdP redirects back to the callback with code+state or error+state
10–11callback: receive the request, read login:{sid1} by the login_sid cookie
12callback: no login:{sid1} → failure (nothing deleted)
13–14callback: wrong state → delete login:{sid1}, failure
15–16callback: error present → delete, mapping from Day 4, Part 2
17–18callback: code missing → delete, failure
19 (+ Note)callback: token request, retry ≤ 2 (Day 4, Part 1)
20–21callback: token request fails → delete, failure
22 (+ Note)callback: receive tokens, verify id_token's 7 items (Day 3, Part 3)
23–24callback: verify fails → delete, failure
25–28callback: Account Attribute API; not eligible → delete, failure (Day 6, Part 2)
29–32callback: Login Status API; fails/not allowed → delete, failure (Day 6, Part 2)
33–34 (+ Note)callback: delete SessionID1, create a new SessionID2 (Day 2, Part 1; Day 2, Part 3 on session fixation)
35callback: Login History (best effort, intentionally fire-and-forget)
36 (+ Note)callback: 302 to successUrl, set sid/xsrf/uid (Day 1, Part 3)

When reviewing, go both ways: every table row must have both columns filled; a row with one empty column is where the spec and the diagram diverge.

5.2 RFC/OIDC ↔ step matching table

This table is the "output" of Days 3–4 in the course roadmap; it proves the flow follows the standards and points out which parts are MemberPortal's own decisions (not in any standard).

StandardSectionRequirementStep/value in the diagramMemberPortal note
RFC 6749§4.1.1Authorization request: response_type=code, client_id, redirect_uri, scope, stateSteps 4–5state mandatory (RFC: RECOMMENDED)
RFC 6749§4.1.2Authorization response: code, stateStep 8
RFC 6749§4.1.2.1Error response: error, error_descriptionStep 9, handled at 15–16Own mapping (Day 4, Part 2)
RFC 6749§4.1.3Token request: grant_type, code, redirect_uri, client_id (+ client auth)Step 19Form-urlencoded; client_secret in the body
RFC 6749§10.12CSRF protection via state bound to the user-agent sessionSteps 13–14, login:{sid1} + cookie login_sidServer-side session instead of a signed cookie
RFC 7636§4.1–4.2code_verifier 43–128 characters; code_challenge S256Note after step 2, steps 4–532 bytes base64url; padding removal stated explicitly
RFC 7636§4.5–4.6Send code_verifier in the token request; AS verifiesStep 19
OIDC Core§3.1.2.1scope contains openid; nonce; max_age (if auth_time is needed)Steps 4–5scope=openid profile; web login does not send max_age
OIDC Core§3.1.3.3Token response contains id_tokenStep 22
OIDC Core§3.1.3.7ID Token validation: iss, aud, exp, signature, nonce, auth_timeNote after step 22+ custom claim connection (own)
OIDC Core§5.1.2Additional claims use collision-resistant namesClaim https://claims.example.com/*
OAuth Security BCP (RFC 9700)§2.1.1PKCE for every clientNote after step 2, steps 4–5Applied even for a confidential client
OAuth Security BCP (RFC 9700)§2.1.2No implicit flow, no tokens in URLsWhole diagramOnly code passes through the browser
Browser-Based AppsBFF patternTokens on the server, session cookie in the browserSteps 34, 36Reason for choosing the architecture (Day 1, Part 1)
Not in any standard—Two kinds of session, delete SessionID1 in every error branch; Account Attribute/Login Status before creating the sessionSteps 25–33Own decision; record a "design rationale"

6. When to split diagrams

The diagram in section 3 is already at the limit of readability. MemberPortal splits out separate diagrams for:

  • Logout (3 endpoints, Day 4, Part 2): a different flow, different participants.
  • SSO from the app WebView (Day 6, Part 1): has the Native App and SSO Token Verify API participants.
  • Web / native step-up and MFA management (Day 7, Part 1): several clients, different sub-sessions.
  • BFF startup (Day 4, Part 1): no browser, so draw it as a flowchart instead of a sequence.

Rule: split when (a) the participant set differs, or (b) there are more than ~40 arrows, or (c) there are more than 3 levels of nested alt. Sub-diagrams must be named and linked from the corresponding endpoint.


Review Questions

  1. How does client_credentials differ from authorization_code? Why can only a confidential client use it?

    Show answer

    authorization_code: a user interacts through the browser, the token represents the user (has an id_token, sub = user), and it lives with the user session. client_credentials: no user, the client authenticates itself with client_id + client_secret, the token represents the client itself (no id_token), permissions are granted by the tenant admin, and it is shared by every request of the instance. Only a confidential client can use it because this grant relies entirely on client_secret; a public client (SPA, mobile) cannot keep a secret, so anyone could obtain the system token.

  2. MemberPortal chooses fail-fast when boot cannot obtain the Management API token. Give the reasons and one case where a degraded start would be more reasonable.

    Show answer

    Reasons for fail-fast: a client_credentials error is almost always a wrong configuration/secret, so detecting it right at deploy time is better than when the first customer withdraws money; the readiness probe is honest; the orchestrator restarts automatically. A degraded start is reasonable when the Management API only serves a secondary, rarely used feature, and downtime of the IdP Management API (not the Authentication API) is treated as a separate incident that must be isolated; in that case the spec must state clearly which endpoints are affected and what error they return. The key point: record the decision and the reason in the spec, do not let developers choose on their own.

  3. What does MemberPortal's "retry at most 2 times" mean in total requests, and which errors are NOT retried?

    Show answer

    3 requests in total (1 original + 2 retries); the spec writes "3 calls in total" explicitly to avoid differing interpretations. Retry only on timeout and 5xx. No retry on 4xx (400/401/403: wrong configuration, wrong secret, wrong grant), no retry on invalid_grant when exchanging code (code expired/already used/wrong PKCE; the flow must start over), and 429 is not retried under the basic policy but logged as a warning because retrying immediately makes rate limiting worse.

  4. Why refresh the token when "< 5 minutes remain" rather than on a 401?

    Show answer

    Waiting for a 401 means a real customer's request suffers latency or failure, and every place that calls the Management API needs retry-on-401 logic. Refreshing early with a 5-minute margin: there is enough time for one token request, including 2 retries (5s timeout each), to complete before the old token expires, so no customer request ever hits an expired token; meanwhile only 5 minutes out of a ~24h lifetime are wasted. Combined with collapsing concurrent requests (inflight), it does not request several tokens at once.

  5. Why is a client_credentials token obtained at boot enough (and appropriate) to call /api/v2/users/{sub}, and what are the accompanying security conditions?

    Show answer

    Because reading user metadata is a system permission (the read:users permission granted by the tenant admin to portal-management), not an end-user permission; a user token from Universal Login does not and should not have Management API scopes. The BFF acts as a trusted subsystem: it uses the system token but only within the context of an authenticated user. Conditions: (1) the sub in the URL must come from a verified id_token or from sess:{id}, never from a query/cookie; (2) minimum permissions (no delete:users, no permissions on clients); (3) the token stays only in memory, is not logged, and is not in Redis.

  6. Why must the spec state the exact string and the source of error_description when branching on it?

    Show answer

    Because RFC 6749 only standardizes error, while error_description is a free-form string filled in by the IdP (Auth0 core, custom DB script, Action, or Keycloak). Branching on it is an implicit contract between the BFF and the IdP configuration side: changing the string on one side without the other turns the "maintenance" screen into "login failed" without anyone reporting an error. Recording the string and who owns it (fixed by Auth0 vs the maintenance:: prefix agreed with operations) allows changes on both sides to be reviewed together.

  7. Why must the "maintenance::" row be matched before the error == access_denied row?

    Show answer

    Because the custom DB script reports maintenance by throwing an error, and Auth0 passes that error back to the BFF as error=access_denied with error_description=maintenance::.... If you check error == access_denied first, every maintenance case falls into "Login failed", customers think they entered the wrong password and call the hotline in bulk. The spec must say "match in order from top to bottom" and put the specific condition (on error_description) before the general condition (on error).

  8. Does separating the "Your account is restricted from logging in" screen cause user enumeration? What is MemberPortal's argument?

    Show answer

    The risk is low and intentionally accepted. Auth0 only returns user is blocked after the user passes the authentication step (or for a brute-force block on the exact account under attack, in which case the block is doing its job). An attacker without the password only sees "wrong password" on the IdP page and never reaches the callback. Benefit: the genuine account owner knows to contact support instead of uselessly changing the password. Conversely, access_denied due to account type is merged into "Login failed" because it could leak information before identity is proven. Principle: details only for people who have authenticated.

  9. Why does the client stepup-password-web have two login callback URLs instead of one branching callback or two clients?

    Show answer

    The two callbacks serve two purposes that differ in the kind of sub-session they create: /auth/stepup/callback creates stepup:{id} with a fixed TTL of 600s (proof of authentication for withdrawing money/changing the account), while /auth/stepup/mfa-callback creates stepup-mfa:{id} with TTL = expires_in because the access_token is actually used to call /mfa/*. A single callback branching on context bloats the endpoint and makes the two kinds of session easy to confuse; two clients increase the number of secrets to manage without any extra benefit. The IdP allows one client to have several callbacks in the allow-list, as long as every URL has a real endpoint, checks state, and is recorded in the spec.

  10. Why must /auth/web/logout delete sess:{id} before redirecting to the IdP, and why does it still redirect when there is no session?

Show answer

Deleting first puts the BFF in a safe state regardless of whether IdP logout succeeds (IdP down, misconfigured returnTo, customer closes the tab midway): the BFF session is what allows calling /api/s/*, so it must die immediately. It still redirects to the IdP when sess:{id} is gone (TTL expired) because the SSO session at Auth0 may still be alive; if it only returned 401 or "you are not logged in", a user on a public machine would walk away thinking they had logged out, and the next person clicking "Sign in" would get straight in because web login does not send prompt=login.

  1. What does the "1-to-1 match" principle between the sequence diagram and Processing details mean, and how does MemberPortal maintain it?
Show answer

Every arrow/branch in the diagram corresponds to exactly one step in the "Processing details" bullets and vice versa; no step exists on only one side. It is maintained by: (1) autonumber on the diagram and bullets that record the step number in brackets; (2) a two-column matching table in the spec, where a row with one empty column signals divergence; (3) CI running mermaid-cli so the diagram always renders; (4) a PR convention: changing one side requires changing the other, and reviewers reject PRs that change only one side.

  1. In the Web login diagram, at which steps does code_verifier appear and where does it not appear? Why does that matter?
Show answer

[CREATE] at the CSPRNG generation step, stored in login:{sid1}, and [READ] when the BFF POSTs to /oauth/token. It does not appear in the /authorize redirect (only code_challenge, its hash, goes out to the IdP) and never passes through the browser. It matters because that is exactly the guarantee of PKCE (Day 3, Part 2): anyone who intercepts the /authorize URL or the callback still has no verifier to exchange the code. If a diagram shows the verifier passing through the browser, the reviewer must block it immediately.

  1. Why should Redis be a separate participant in the login diagram?
Show answer

Because the session SET/GET/DEL operations are exactly where the lifecycle of the two kinds of session is shown (SessionID1 lives from when login starts until the callback finishes; SessionID2 is created only after all checks) along with the rule "every error branch DELs login:{sid1}". If Redis is hidden in a Note, the reviewer cannot count whether any branch forgets to delete, and the tester does not know which Redis key to check at each step. It also makes session fixation clear: SET sess:{sid2} with a new id, not reusing sid1.

  1. List three common Mermaid syntax errors in long diagrams and how MemberPortal detects them early.
Show answer

(1) Missing end for nested alt/opt/loop → "Expecting 'end'"; (2) special characters such as ; or # unescaped in a message → "Expecting 'NEWLINE'"; (3) a mistyped, undeclared participant alias. Detect them early with npx -y @mermaid-js/mermaid-cli -i file.md -o /tmp/out.md running in CI for every PR that changes docs; a non-zero exit code with the error line, instead of waiting for GitHub's generic "Unable to render".

  1. The RFC ↔ step matching table has a "Not in any standard" row. Why must rows like that be recorded?
Show answer

To distinguish requirements of the standard (which must not be dropped, e.g. checking nonce, aud) from MemberPortal's own decisions (two kinds of session, calling Account Attribute/Login Status before creating the session, deleting SessionID1 in every error branch). Own decisions need a "design rationale" column so later readers understand the reason and can change them consciously; if they are mixed with standard requirements, either nobody dares to change anything, or conversely someone drops the nonce check too, thinking it is also just an "internal convention".

Hands-on Exercises

Exercise 1: Obtain a Management API token with curl

On an Auth0 sandbox tenant (Day 3, Part 1), create a Machine-to-Machine application, authorize it for the Management API and grant only read:users. Call:

curl -s -X POST https://<tenant>.auth0.com/oauth/token \
  -H 'content-type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials' -d 'client_id=<M2M client id>' \
  -d 'client_secret=<secret from the dashboard, do not save it to a file>' \
  -d 'audience=https://<tenant>.auth0.com/api/v2/'

Decode the access_token payload, call GET /api/v2/users/{sub}, then try a PATCH on the same user. Expected output: the scope in the token contains only read:users; the GET succeeds, the PATCH gets 403 insufficient_scope. Record exp - iat to know the token lifetime.

Exercise 2: Write getManagementToken() with tests

Implement the function from section 4 with a mocked fetch. Write tests: (a) 20 concurrent callers create only 1 request; (b) token with 4 minutes left → new request; with 6 minutes left → none; (c) 503 twice then 200 → success with 3 requests; 503 three times → throws. Expected output: 4 green tests; log the number of mock calls.

Exercise 3: Write the "Startup processing" section for a variant

Suppose a new requirement: the BFF must also call an internal "Feature Flag API" at boot to learn PASSKEY_ENABLED. Rewrite the "Startup processing" section with the new step, decide between fail-fast and fallback (use the env value), and give the reason. Expected output: a numbered list of steps, each stating the action on failure; 1 "design rationale" paragraph.

Exercise 4: Reproduce all 4 error rows on the sandbox

On the Auth0 sandbox: (a) block a user in the dashboard; (b) disable the connection for the application; (c) write a post-login Action api.access.deny('maintenance::test'); (d) api.access.deny('not-eligible'). For each case, log in and record the exact error + error_description received at the callback. Expected output: a 4-row table "scenario / error / error_description / corresponding mapping row"; note which cases do not come back to the callback.

Exercise 5: Reproduce allow-list errors

Call /authorize with a redirect_uri that differs by 1 character from the configuration (add a trailing /). Then try a returnTo that is not in Allowed Logout URLs. Expected output: describe the error screen Auth0 shows in each case and why it does not redirect to the BFF; write a 1-line recommendation for the deploy checklist.

Exercise 6: Write the spec for the 3 logout endpoints for Keycloak

Write the Item/Required/Rule table and the processing details for /auth/web/logout, logout-callback, logout-complete when idProvider = keycloak, using the end_session endpoint with client_id + post_logout_redirect_uri. Add an "Error branches" section with at least 4 rows. Expected output: 3 tables + a list of error branches, consistent with the Auth0 version in section 6.

Exercise 7: Redraw from memory

Close the lesson and draw the Web login sequence diagram in Mermaid within 30 minutes, with autonumber, a Redis participant, at least 4 alt branches, and [CREATE]/[READ]/[DELETE] markers for state, nonce, code_verifier, SessionID1, SessionID2. Render it with mermaid-cli. Expected output: a .mmd file that renders without errors; compare it yourself with the diagram in section 3 and list the steps you missed.

Exercise 8: Find a spec bug through the diagram

Take the diagram from section 3, deliberately delete the DEL login:{sid1} command in the "Verify fails" branch, and give it to a colleague (or reread it yourself after 1 day) to find it. Then write a test case for the tester based on that bug: action steps, Redis key to check, expected result. Expected output: 1 test case of 4-6 lines, with the Redis key name and when to check it.

Exercise 9: RFC matching table for logout

Draw the sequence diagram of the 3 logout endpoints (Day 4, Part 2) in Mermaid, then build a matching table against OIDC RP-Initiated Logout 1.0 (§2 Redirection, post_logout_redirect_uri, client_id/id_token_hint) and state clearly which rows are own decisions (deleting the BFF session before redirecting, still redirecting when there is no session). Expected output: a diagram that renders + a table with ≥ 5 rows, including at least 2 "Not in any standard" rows.

References


Next lesson →