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_credentialsgrant is, how it differs fromauthorization_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/logoutand Keycloakend_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/elseto represent the main error branches instead of drawing many separate diagrams - Check Mermaid syntax with
mermaid-clibefore 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:
| Task | When | Is 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 enrollment | After the MFA step | Same as above |
| Load the JWKS of Auth0 and Keycloak | At startup | No |
| Check that the IdP configuration is still correct (client exists, callback URL) | At startup / health check | No |
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.
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 API | Management API | |
|---|---|---|
| Base URL | https://login.example.com/ | https://login.example.com/api/v2/ |
| What it does | /authorize, /oauth/token, /v2/logout, /userinfo, /mfa/*, /.well-known/jwks.json | CRUD users, clients, connections, read/write user_metadata, manage authenticators |
| Who calls it | Browser (redirect) and BFF (token exchange) | BFF only, server-to-server |
| Token required | None (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 client | portal-web, the stepup-* clients | portal-management |
| Grant | authorization_code, mfa | client_credentials |
Three questions that the spec's IdP client table (Day 7, Part 3 teaches how to write it) must answer for portal-management:
- Which permissions are granted on the Management API? MemberPortal:
read:users,update:users,read:users_app_metadata,update:users_app_metadata. Nodelete:users, nocreate:clients. The principle of least privilege. - Is there a callback URL? No.
client_credentialsdoes not redirect. The client table puts "—" in the callback column so readers do not wonder. - Who holds the secret? The BFF, via the env
IDP_MGMT_CLIENT_SECRET(separate fromIDP_CLIENT_SECRETofportal-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.
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.
| Strategy | Problem |
|---|---|
| Request when an API call returns 401 | The 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 request | Wasteful, easily rate-limited by Auth0 |
| Request a buffer period before expiry | MemberPortal'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.
| Scenario | Retry? | Reason |
|---|---|---|
| Timeout (no response received) | Yes, ≤ 2 times | Could be a transient network issue |
| 500, 502, 503, 504 | Yes, ≤ 2 times | Transient IdP-side error |
| 429 Too Many Requests | No in the basic policy; log a warning | Retrying immediately makes it worse; needs a longer backoff or investigation |
| 400, 401, 403 | No | Wrong configuration / wrong secret / wrong grant; retrying is useless and hides the real error |
invalid_grant when exchanging code | No | Code 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:usersacross the whole tenant. - The
client_credentialstoken ofportal-managementsays "client portal-management has been granted the permissionsread:users,update:users,read:users_app_metadata,update:users_app_metadataby the tenant admin". It is a system permission, independent of who is logged in. The BFF uses it to callGET /api/v2/users/{sub}withsubtaken from the verified id_token (Day 3, Part 3).
Two accompanying security conditions that the spec states explicitly:
submust come from a verified token or fromsess:{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.- Minimum permissions.
portal-managementhas nodelete:usersand 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
- Validate env (required list: ...). Missing → FATAL, stop.
- Connect to Redis. Fail → FATAL, stop.
- Obtain the Management API token (client
portal-management, grantclient_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. - Load the Auth0 JWKS; if
ALT_IDP_ENABLED=true, load the Keycloak JWKS. Retry as in step 3. Fail → FATAL, stop. - Readiness OK.
Client table (excerpt)
| Client | Grant | Callback | Management API permissions | Purpose | Design rationale |
|---|---|---|---|---|---|
portal-management | client_credentials | — | read:users, update:users, read:users_app_metadata, update:users_app_metadata | BFF reads/writes user metadata for step-up/MFA | Needs 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:
| Parameter | Required | Meaning |
|---|---|---|
error | Yes | Standard error code: invalid_request, unauthorized_client, access_denied, unsupported_response_type, invalid_scope, server_error, temporarily_unavailable |
error_description | No | Human-readable string, freely filled in by the IdP |
error_uri | No | Documentation 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.
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 side | What to delete | Screen / action | Why it is separate |
|---|---|---|---|---|---|
| 1 | error_description == "user is blocked" | Account blocked by Auth0 (brute-force, admin) | login:{id} | "Your account is restricted from logging in" with instructions to contact support | The customer needs to know they must do something else (call the hotline) instead of retrying |
| 2 | error_description == "connection is not enabled" or error_description starts with maintenance:: | Operations disabled the connection or the custom DB reports maintenance | login:{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 |
| 3 | error == "access_denied" (any other error_description) | IdP rejects by account type (Day 6, Part 2), user cancels, Action deny | login:{id} | "Login failed", redirect to failureUrl if present | Merged so the specific reason is not revealed |
| 4 | Any other error (server_error, temporarily_unavailable, invalid_request not covered by row 2...) | IdP or configuration error | login:{id} | "Login failed" + log the error code at ERROR level for operations to investigate | No different action for the customer |
Four rules to take away:
- Matching order matters. Row 2's
maintenance::comes witherror=access_denied; if you checkerror == access_deniedfirst, every maintenance error becomes "Login failed". The spec says "match in order from top to bottom". - Every branch deletes
login:{id}. The same use-once rule as Day 3, Part 2. - The
error_descriptionstring 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. - 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"):
| Factor | Assessment |
|---|---|
| Who sees the message | Someone 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 customer | Very high: they know to call the hotline instead of uselessly changing the password, reducing support tickets |
| Risk | Low, because to reach this branch the attacker must have the password; in that case the block is protecting the account exactly as designed |
| Conclusion | Separate 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_uriin/authorizeand in/oauth/tokenmust be byte-for-byte identical to each other and to the Auth0 configuration, includinghttps, 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 thecash-out/withdrawal-accountcontext, creatingstepup:{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 createstepup-mfa:{id}with TTL =expires_ininstead ofstepup:{id}600s (Day 7, Part 1).
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| Endpoint | What it does | Why it is separate |
|---|---|---|
GET /auth/web/logout | Reads the session (does not require X-XSRF-TOKEN, see design rationale), deletes sess:{id} first, clears cookies, redirects to IdP logout | Deleting the BFF session first means the BFF side is safe even if IdP logout fails |
GET /auth/web/logout-callback | Where the IdP returns (listed in Allowed Logout URLs); clears cookies again; redirects to complete | A technical URL with no content; separated so the UI does not depend on the URL name the IdP needs |
GET /auth/web/logout-complete | Page shown to the customer | Can 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
| Auth0 | Keycloak (standard OIDC) | |
|---|---|---|
| Endpoint | GET /v2/logout | GET /realms/{realm}/protocol/openid-connect/logout |
| Return parameter | returnTo (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 identification | client_id | client_id or id_token_hint (old id_token JWT) |
| Logout from an external (federated) IdP | federated | Depends on the configured identity provider |
| For MemberPortal | Use client_id + returnTo | Use 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
| Scenario | Handling |
|---|---|
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 back | The 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-list | Auth0 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:
error_description=user is blocked→ go to the "Your account is restricted from logging in" screen.error_description=connection is not enabled, or starts withmaintenance::→ go to the "Login is under maintenance" screen.- Otherwise → go to "Login failed" (
failureUrlif present, the login page by default).
- Log:
bffErrCode,error,error_description(do not logstate, 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
| Location | Item | Required | Rule |
|---|---|---|---|
| cookie | sid | No | Present → delete sess:{sid}; absent → skip |
| header | X-XSRF-TOKEN | No | Not 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:
| Reader | Uses the diagram to |
|---|---|
| New developer | Grasp the big picture in 5 minutes before reading 3 pages of bullets |
| Tester | Count the requests to observe in DevTools, know where cookies are set |
| Security reviewer | See 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:
autonumberis 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, notNotes; [CREATE]/[READ] markers written in aNoteare 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
endRead 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 (onlycode_challengegoes 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:
| Message | Cause | Fix |
|---|---|---|
Parse error ... Expecting 'end' | Missing end for alt/opt/loop | Count the alt/opt/loop and end keywords; consistent indentation helps spot it |
Expecting 'NEWLINE' ... got 'TXT' | Unescaped ; or # in a message | Replace with a word or use #59; |
| Text overflows | Message too long | Break it with <br/> |
| Arrow to an undeclared participant | Mistyped alias | Declare 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 / 9 | IdP redirects back to the callback with code+state or error+state |
| 10–11 | callback: receive the request, read login:{sid1} by the login_sid cookie |
| 12 | callback: no login:{sid1} → failure (nothing deleted) |
| 13–14 | callback: wrong state → delete login:{sid1}, failure |
| 15–16 | callback: error present → delete, mapping from Day 4, Part 2 |
| 17–18 | callback: code missing → delete, failure |
| 19 (+ Note) | callback: token request, retry ≤ 2 (Day 4, Part 1) |
| 20–21 | callback: token request fails → delete, failure |
| 22 (+ Note) | callback: receive tokens, verify id_token's 7 items (Day 3, Part 3) |
| 23–24 | callback: verify fails → delete, failure |
| 25–28 | callback: Account Attribute API; not eligible → delete, failure (Day 6, Part 2) |
| 29–32 | callback: 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) |
| 35 | callback: 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).
| Standard | Section | Requirement | Step/value in the diagram | MemberPortal note |
|---|---|---|---|---|
| RFC 6749 | §4.1.1 | Authorization request: response_type=code, client_id, redirect_uri, scope, state | Steps 4–5 | state mandatory (RFC: RECOMMENDED) |
| RFC 6749 | §4.1.2 | Authorization response: code, state | Step 8 | |
| RFC 6749 | §4.1.2.1 | Error response: error, error_description | Step 9, handled at 15–16 | Own mapping (Day 4, Part 2) |
| RFC 6749 | §4.1.3 | Token request: grant_type, code, redirect_uri, client_id (+ client auth) | Step 19 | Form-urlencoded; client_secret in the body |
| RFC 6749 | §10.12 | CSRF protection via state bound to the user-agent session | Steps 13–14, login:{sid1} + cookie login_sid | Server-side session instead of a signed cookie |
| RFC 7636 | §4.1–4.2 | code_verifier 43–128 characters; code_challenge S256 | Note after step 2, steps 4–5 | 32 bytes base64url; padding removal stated explicitly |
| RFC 7636 | §4.5–4.6 | Send code_verifier in the token request; AS verifies | Step 19 | |
| OIDC Core | §3.1.2.1 | scope contains openid; nonce; max_age (if auth_time is needed) | Steps 4–5 | scope=openid profile; web login does not send max_age |
| OIDC Core | §3.1.3.3 | Token response contains id_token | Step 22 | |
| OIDC Core | §3.1.3.7 | ID Token validation: iss, aud, exp, signature, nonce, auth_time | Note after step 22 | + custom claim connection (own) |
| OIDC Core | §5.1.2 | Additional claims use collision-resistant names | Claim https://claims.example.com/* | |
| OAuth Security BCP (RFC 9700) | §2.1.1 | PKCE for every client | Note after step 2, steps 4–5 | Applied even for a confidential client |
| OAuth Security BCP (RFC 9700) | §2.1.2 | No implicit flow, no tokens in URLs | Whole diagram | Only code passes through the browser |
| Browser-Based Apps | BFF pattern | Tokens on the server, session cookie in the browser | Steps 34, 36 | Reason 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 session | Steps 25–33 | Own 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
-
How does
client_credentialsdiffer fromauthorization_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 anid_token,sub= user), and it lives with the user session.client_credentials: no user, the client authenticates itself withclient_id+client_secret, the token represents the client itself (noid_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 onclient_secret; a public client (SPA, mobile) cannot keep a secret, so anyone could obtain the system token. -
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_credentialserror 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. -
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_grantwhen exchangingcode(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. -
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. -
Why is a
client_credentialstoken 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:userspermission granted by the tenant admin toportal-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) thesubin the URL must come from a verified id_token or fromsess:{id}, never from a query/cookie; (2) minimum permissions (nodelete:users, no permissions on clients); (3) the token stays only in memory, is not logged, and is not in Redis. -
Why must the spec state the exact string and the source of
error_descriptionwhen branching on it?Show answer
Because RFC 6749 only standardizes
error, whileerror_descriptionis 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 themaintenance::prefix agreed with operations) allows changes on both sides to be reviewed together. -
Why must the "maintenance::" row be matched before the
error == access_deniedrow?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_deniedwitherror_description=maintenance::.... If you checkerror == access_deniedfirst, 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 (onerror_description) before the general condition (onerror). -
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 blockedafter 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_denieddue 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. -
Why does the client
stepup-password-webhave 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/callbackcreatesstepup:{id}with a fixed TTL of 600s (proof of authentication for withdrawing money/changing the account), while/auth/stepup/mfa-callbackcreatesstepup-mfa:{id}with TTL =expires_inbecause the access_token is actually used to call/mfa/*. A single callback branching oncontextbloats 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, checksstate, and is recorded in the spec. -
Why must
/auth/web/logoutdeletesess:{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.
- 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.
- In the Web login diagram, at which steps does
code_verifierappear 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.
- 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.
- 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".
- 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
- RFC 6749 §4.4 — Client Credentials Grant
- Auth0 Docs — Client Credentials Flow
- Auth0 Docs — Management API Access Tokens
- Auth0 Management API v2 — Users
- Auth0 Docs — Rate Limit Policy
- Keycloak Docs — Service Accounts (client credentials)
- RFC 6749 §4.1.2.1 — Error Response
- RFC 6749 §3.1.2.2 — Registration Requirements (redirect URI)
- OpenID Connect RP-Initiated Logout 1.0
- Auth0 Docs — Logout (
/v2/logout,returnTo) - Auth0 Docs — Custom Database Action Script Errors
- Auth0 Actions —
api.access.deny - Keycloak Docs — Logout endpoint
- OWASP — Authentication Cheat Sheet (error messages, enumeration)
- Mermaid — Sequence diagrams
- mermaid-cli (mmdc)
- RFC 6749 — OAuth 2.0
- RFC 7636 — PKCE
- OpenID Connect Core 1.0
- OAuth 2.0 Security Best Current Practice — RFC 9700
- OAuth 2.0 for Browser-Based Apps