devHọc Dev

Week 2 - Day 6: Multi-channel SSO, Three-Layer Account Control, and Backup IdP

Week 2 – Day 6

This lesson combines 3 topics: Multi-channel and SSO from an app WebView using an opaque token, Three-layer account type control and post-login processing, Backup IdP and health check.

Learning Objectives

  • Understand why a single BFF serves multiple channels (Web, App, Operator) yet uses only one session model
  • Design an SSO flow from a native app into a WebView using an opaque token cookie injected by the app
  • Distinguish opaque token + server-to-server verify from a self-verifiable id_token
  • Internalize the principle "User-Agent is only for routing, never for granting access"
  • Write complete 401/403 handling branches on both the UI side and the BFF side for app SSO
  • Clearly distinguish authentication (who you are) from authorization by account type (whether you may use this system)
  • Understand the three-layer defense in depth model: IdP, application, BFF; know which layer is the deciding one
  • Design post-login processing: distinguish "login-blocking" APIs from "best-effort" APIs
  • Write complete error branches for each post-login API: which session to delete, whether to set cookies, which screen to go to
  • Recognize the vulnerabilities that appear when a layer is skipped or when two layers return conflicting results
  • Understand why a fintech system needs a backup IdP (Keycloak) alongside the primary IdP (Auth0)
  • Design the IdP selection step before starting the Authorization Code flow, based on an on/off flag and the Auth Health API
  • Explain why the health check result must be cached and why idProvider is stored in SessionID1
  • Know how to preload the JWKS of both IdPs at startup so the callback does not depend on additional network calls
  • Evaluate the fail-open decision when the Auth Health API itself fails: why it was chosen, what the risks are, and how to write it in the spec

Part 1: Multi-channel and SSO from an App WebView Using an Opaque Token

1. Multi-channel: one session model, many ways to issue it

MemberPortal has three different entry points, but once login is complete, every /api/s/* request is checked the same way: cookie sid → Redis sess:{id} → xsrf match. The only difference between channels lies in the step that issues SessionID2.

┌──────────────────────────────────────────────────────────┐│HowSessionID2isissued│├──────────────────┬──────────────────┬────────────────────┤│Channel=Web│Channel=App│Channel=Operator││OIDCAuthCode│SSOopaquetoken│Operatorlogin││+PKCEwithIdP│+verifyAPI│+AccountStatus│└────────┬─────────┴────────┬─────────┴─────────┬──────────┘│││▼▼▼┌──────────────────────────────────────────────────────────┐│sess:{id}={accountNo,sub,xsrfToken,channel,...}││cookiesid(HttpOnly)+xsrf(JS-readable)+uid│└──────────────────────────┬───────────────────────────────┘│▼┌──────────────────────────────────────────────────────────┐│All/api/s/*:SessionCheck→XsrfCheck→proxy│└──────────────────────────────────────────────────────────┘

Why store channel in the session?

Not for general authorization, but because some sub-flows accept only one channel. The typical example: the Native version of step-up authentication (Day 7, Part 1) only accepts sessions with channel = App, because its callback returns to the app via a Universal Link. A Web session entering the Native flow would have nowhere to call back to, so the BFF rejects it up front instead of letting the error happen mid-flow.

ChannelInitiated byAuthentication methodNotes
WebUser opens a browserOIDC Authorization Code + PKCE with Auth0/KeycloakDefault flow (Week 1, Day 3)
AppNative app opens a WebViewAPP_SSO_TOKEN cookie injected by the app, verified by the BFF server-to-serverToday's lesson
OperatorOperations staffDedicated endpoint /auth/operator/loginDay 7, Part 2

Self-check question: if the three channels used three different kinds of session (three Redis prefixes, three cookies), how complex would the /api/s/* middleware become? This is why the project chose a single session model and pushed the differences into the issuing step.

2. The SSO problem from a native app into a WebView

ACME Trade App (iOS/Android) already has its own app login session. When the user taps a feature served by MemberPortal, the app opens a WebView to https://portal.example.com/.... Requirement: the user must not have to log in again.

There are three common approaches:

ApproachDescriptionProblem
Open the WebView and let the web OIDC flow runThe user has to re-enter the passwordPoor experience, SSO goal fails
App passes the app's access_token in the WebView URLToken leaks via URL, history, logsViolates the "token never leaves the server" principle
App injects an opaque token into the WebView cookie jar, BFF verifies server-to-serverRequires a dedicated verify API on the core system sideThe approach MemberPortal chose

The app-injected cookie is named APP_SSO_TOKEN: a 64-character hex string with no structure; the BFF cannot read its contents on its own. Its value only has meaning to the SSO Token Verify API on the core system side.

sequenceDiagram
    participant App as ACME Trade App
    participant W as WebView
    participant BFF
    participant Core as Core system
    App->>W: set-cookie APP_SSO_TOKEN=<64hex> into cookie jar
    App->>W: open https://portal.example.com/page
    W->>BFF: GET /api/s/profile (no sid yet)
    BFF-->>W: 401 session invalid
    Note over W: UA matches app? → POST /auth/app/login
    W->>BFF: POST /auth/app/login
    BFF->>Core: verify(APP_SSO_TOKEN) [API key]
    Core-->>BFF: { sub, accountNo, accountType, passkeyFlag }
    Note over BFF: accountType OK? → create sess:{id}
    BFF-->>W: 200 + Set-Cookie sid/xsrf/uid
    W->>BFF: retry GET /api/s/profile (with X-XSRF-TOKEN)
    BFF-->>W: 200 data

3. UI side: handling 401 based on User-Agent

This logic usually lives in the frontend's HTTP interceptor. The spec must state it clearly so the frontend and the BFF share the same understanding.

Receive401responsefrom/api/s/*│├─body.bffErrCode==STEPUP_REQUIRED?──yes──▶Startstep-upflow(Day7,Part1),DONOTclearcookies,stop│├─AlreadytriedSSOinthisrequest?──yes──▶Clearcookies(exceptAPP_SSO_TOKEN),sessionStorage│→"Loginfailed"screen│└─notyet│├─UAmatchespatternACMETradeApp/*?│││├─yes──▶POST/auth/app/login││├─200→retrytheoriginalrequest(exactlyonce)││├─403→"Loginfailed"screen││└─5xx→systemerrorscreen│││└─no──▶redirect/auth/web/login?successUrl=<currenturl>

Four points the spec must state clearly:

  1. Check bffErrCode first. A 401 with STEPUP_REQUIRED (Day 7, Part 1) means the login session is still alive and only proof of re-authentication is missing; applying the generic 401 procedure here would log the user out by mistake.
  2. Retry exactly once. If the original request still returns 401 after a successful SSO (for example, the session was deleted elsewhere), do not loop forever.
  3. 403 is not 401. A 403 from /auth/app/login means "the BFF knows who you are, but you are not eligible" (invalid token, or account type not allowed). The UI should not proceed to web login, because that user would also be rejected at the IdP.
  4. Do not delete APP_SSO_TOKEN. This cookie belongs to the app; the BFF and the UI do not own it. If it is deleted, the app has no way to SSO again within the same WebView session.

4. BFF side: POST /auth/app/login

Endpoint table

ItemValue
OverviewIssue SessionID2 for channel App based on the APP_SSO_TOKEN cookie
Method / EndpointPOST /auth/app/login
BodyNone (or {})
LocationItemRequiredValue
headerUser-Agent✓Must match pattern ACMETradeApp/*
cookieAPP_SSO_TOKEN✓64 hex characters injected by the app

Processing details

1.CheckthatUser-Agentmatchestheapppattern└─nomatch→403,donotcalltheverifyAPI(avoidwastingAPIquotaandblockuseofthisendpointfromregularbrowsers)2.ReadAPP_SSO_TOKENfromthecookie└─missing,ornot64hex→4033.CalltheSSOTokenVerifyAPI(server-to-server,APIkeyheaderfromenv)├─5xx/timeout→retryupto2times→stillfailing→503├─tokeninvalid/expired→403└─OK→receive{sub,accountNo,accountType,passkeyFlag}←accountNocomesfromhere,NOTfromtheclient4.accountType≠online-trading→403(nosessioncreated)5.CalltheAccountAttributeAPIwithaccountNo→re-confirmtheaccounttype(Day6,Part2)└─notonline-trading→4036.CalltheLoginStatusAPI├─error→503,nosessioncreated└─isLoginAllowed=false→4037.CreateSessionID2(CSPRNG)+xsrfToken(CSPRNG)sess:{id}={accountNo,sub,xsrfToken,channel:"App",usedPasskey:passkeyFlag}TTL=SESSION_TTL8.LoginHistoryAPI(best-effort,errorsignored)9.Set-Cookiesid(HttpOnly),xsrf,uid→200

Why does the BFF check the UA "again" when the UI already did?

Because the UI runs on the client, any check there is only a UX optimization, not a control. The BFF repeats the check so the endpoint is not called from regular browsers. But remember: the UA is easy to spoof. The BFF's UA check only serves to pick the right processing path; access is granted entirely based on the token verify result and the account type, not on the UA.

UAmatchesappUAdoesn'tmatch┌────────────────┬──────────────────────┐Validtoken│Issuesession│403(wrongroute)│├────────────────┼──────────────────────┤Bad/notoken│403│403│└────────────────┴──────────────────────┘AttackerspoofstheUAbuthasnotoken→still403.AttackerhasatokenbutaregularUA→403,butthisisnotasecuritybarrier,becausetheycanchangetheUA.Therealbarrieris"isthereavalidtokenornot".

5. Opaque token vs id_token: two different trust models

Criterionid_token (OIDC, Week 1, Day 3)APP_SSO_TOKEN (opaque)
Can the BFF verify it on its own?Yes: JWKS signature, iss, aud, exp, nonceNo, must call the SSO Token Verify API
What secret is needed to verify?None (public key from JWKS)A dedicated API key for the verify API (server-side env)
Cost per verificationLocal computation, no network call (after JWKS is cached)One network call to the core system
Immediate revocationHard (token lives until exp)Easy (core system deletes the token → verify fails immediately)
Does the token content mean anything?Yes (claims)No, it is just a handle
Risk if leakedAttacker can read the claims, but cannot use them if the BFF checks nonce/audAttacker can use it until it expires or is revoked

Design lesson: when the system issuing the token and the system verifying it belong to the same organization, an opaque token + verify API is a simple choice with immediate revocation. When the verifying system cannot call the issuing system (third parties, many RPs), a self-verifiable JWT is mandatory.

The spec must clearly describe the retry policy and fallback for the verify API, because this is a new network dependency compared to the OIDC flow:

// Simplified example: verify an opaque token with bounded retry
// Fail-fast (Day 4, Part 1 step 1): missing env means no startup, no placeholder.
const SSO_VERIFY_API_KEY = process.env.SSO_VERIFY_API_KEY;
if (!SSO_VERIFY_API_KEY) throw new Error('SSO_VERIFY_API_KEY is required');

type VerifyResult =
  | { valid: true; sub: string; accountNo: string; accountType: string; passkeyFlag: boolean }
  | { valid: false };

async function verifyAppSsoToken(token: string): Promise<VerifyResult> {
  const MAX_RETRY = 2;
  for (let attempt = 0; attempt <= MAX_RETRY; attempt++) {
    try {
      const res = await http.post(
        `${CORE_API_BASE}/sso/verify`,
        { token },
        {
          headers: { 'X-Api-Key': SSO_VERIFY_API_KEY },   // validated at boot, no fallback
          timeout: 3000,
          // axios THROWS on 4xx/5xx by default → the res.status branches below would never run.
          // validateStatus: () => true so we handle the status ourselves instead of falling into catch.
          validateStatus: () => true,
        },
      );
      if (res.status === 200) return { valid: true, ...res.data }; // { sub, accountNo, accountType, passkeyFlag }
      if (res.status === 401 || res.status === 404) return { valid: false }; // bad token → no retry
      if (res.status >= 500 && attempt < MAX_RETRY) continue;      // retry
      throw new ServiceUnavailableException();                      // 5xx on last attempt → 503
    } catch (e) {
      if (e instanceof ServiceUnavailableException) throw e;
      if (isTimeout(e) && attempt < MAX_RETRY) continue;            // timeout → retry
      throw new ServiceUnavailableException();                      // → 503
    }
  }
  throw new ServiceUnavailableException();
}

Note: the API key value always lives in the secret store/infrastructure and never appears in docs or in example code other than as a placeholder.

6. Common mistakes when writing the spec for the app SSO flow

MistakeConsequenceHow to write it correctly
Not specifying a single retry in the UIInfinite 401 → SSO → 401 loopState explicitly "retry the original request exactly once"
Returning 401 for every error of /auth/app/loginThe UI goes into the 401 branch again → calls SSO againUse 403 for "rejected", 503 for system errors
Clearing all cookies on 401APP_SSO_TOKEN is lost, the app cannot SSO againList the cookies to be cleared and state the exceptions
Checking the UA on only one sideUI and BFF disagree on what "app" meansDefine the UA pattern in one place (common definitions) and have both reference it
Trusting accountType from the verify API and dropping the Account Attribute APIThe two sources diverge when the core system changes the account typeKeep both layers (Day 6, Part 2) and state which layer decides
Not writing channel into the sessionNative step-up cannot tell where the session came fromThe session data model table must include a channel field

Part 2: Three-Layer Account Type Control and Post-Login Processing

1. Authenticated does not mean allowed in

After the id_token is verified (Week 1, Day 3) or APP_SSO_TOKEN is verified (Day 6, Part 1), the BFF knows for certain who the user is. But MemberPortal serves only online trading accounts. Customers with other account types (for example, accounts opened only to receive dividends, corporate accounts, closed accounts) can still log in successfully at the IdP, because the IdP manages a shared identity for all of ACME Securities.

   Authentication                  Authorization by account type
   "Is this really customer        "May this customer use
    number 12345?"                  MemberPortal?"
          │                                  │
          ▼                                  ▼
   IdP confirms via                Someone must look up the account
   password / passkey              type and decide whether to let them in

Design question: who checks the account type, and where? Getting this wrong leads to two opposite kinds of errors: valid customers get blocked, or invalid customers slip through.

2. The three-layer model

MemberPortal checks the account type at three independent layers:

┌─────────────────────────────────────────────────────────────────────────┐│Layer1—IdP(Auth0post-loginAction)││Aftertheuserauthenticates,theActionreadstheaccounttypeand││therequesting`client_id`;invalidpair→`api.access.deny()`→IdP││returnserror=access_deniedtothecallback.BFFshows"Loginfailed".│├─────────────────────────────────────────────────────────────────────────┤│Layer2—Application(ACMETradeApp/website)││ShowstheMemberPortalentrypointonlytoonline-tradingaccounts.││Otherusersdonotseethebutton→fewerpointlesscalls.│├─────────────────────────────────────────────────────────────────────────┤│Layer3—BFF(AccountAttributeAPI)││AfterobtainingaccountNo(fromtheid_tokenortheverifyAPI),the││BFFcallstheAccountAttributeAPI.Notonline-trading→DISCARDthe││sessionjustcreated,donotsetcookies,"Loginfailed".│└─────────────────────────────────────────────────────────────────────────┘
LayerControl typeCan it be bypassed?Role
1. IdPServer-side, enforced by the IdPYes, if the client config or script is wrong, or if another channel does not go through the IdP (app SSO)Blocks early, saves BFF resources
2. ApplicationClient-sideEasily, the user types the URL directlyUX only, not security
3. BFFServer-side, enforced by the BFFHardest, every channel goes through itThe final deciding layer

Principle: layer 2 must never be counted as a security layer. Layer 1 is the front line but depends on configuration outside the BFF. Layer 3 is where the spec must be most detailed because it is the last barrier.

Why not keep only layer 3?

Because layer 1 blocks before the BFF creates any session and before the user even finishes entering the password, reducing the attack surface and load. And layer 2 reduces the number of annoying "Login failed" experiences. But if you had to keep only one layer, it would be layer 3.

Why not keep only layer 1?

Because the app SSO channel (Day 6, Part 1) does not go through the IdP: APP_SSO_TOKEN is verified by the core system, not by Auth0. If you relied only on layer 1, every account type that has the app could get into MemberPortal. This is a textbook example of adding a new channel opening a hole in an existing control layer, and it is why the review checklist (Day 7, Part 3) has the item "is authz at the IdP and at the BFF consistent?".

3. Layer 1 in detail: the allow matrix at the IdP

This layer is implemented with an Auth0 post-login Action (or an equivalent mechanism in another IdP). The Action runs after the user has authenticated and has event.client.client_id and the user info available (app_metadata.accountType, written by the custom database script at login), so it can compare the (client × account type) pair. Note: the custom database login script does not receive client context, only (email, password), so this cannot be done there.

// Auth0 Action (post-login) — simplified
exports.onExecutePostLogin = async (event, api) => {
  // client_id list for portal-web, stepup-passkey-web, stepup-password-web,
  // stepup-passkey-native, stepup-password-native — configured in the Action's Secrets, not hard-coded.
  const allowed = (event.secrets.PORTAL_CLIENT_IDS ?? '').split(',');
  if (!allowed.includes(event.client.client_id)) return;     // other clients are outside this matrix
  if (event.user.app_metadata?.accountType !== 'online-trading') {
    api.access.deny('access_denied');                        // → callback receives error=access_denied
  }
};

Resulting matrix:

Clientonline-tradingOther types
portal-webAllowedaccess_denied
stepup-passkey-web, stepup-password-webAllowedaccess_denied
stepup-*-nativeAllowedaccess_denied

The access_denied result comes back to the BFF callback as:

GET /auth/web/login-callback?state=...&error=access_denied&error_description=...

The BFF handles it according to the mapping table in Day 4, Part 2: delete SessionID1 and go to the "Login failed" screen. Do not show a separate "invalid account type" message, because an overly specific message would reveal to outsiders that the account exists and what type it is (enumeration).

4. Layer 3 in detail: the Account Attribute API in the callback

Where this step sits in /auth/web/login-callback (simplified, relevant branch only):

...verifyid_tokenOK,takeaccountNofromclaimaccount_no│├─CreateSessionID2+xsrfToken(inmemory,cookiesNOTsetYET)│├─CallAccountAttributeAPI(accountNo)│├─5xx/timeout→retry2times→stillfailing→deleteSessionID1,DONOTstoreSessionID2→systemerrorscreen│├─accountType≠online-trading→deleteSessionID1,DONOTstoreSessionID2→"Loginfailed"│└─OK→continue│├─CallLoginStatusAPI(section5)├─Storesess:{id}inRedis,deletelogin:{id}├─LoginHistoryAPI(best-effort)└─Set-Cookiesid/xsrf/uid→302successUrl

Two important details to write in the spec:

  1. Order: check first, persist later. SessionID2 is written to Redis and the cookies are set only after all login-blocking APIs have passed. That way there is never a moment when an invalid account has a live session in Redis, not even for a few milliseconds.
  2. accountNo comes from the id_token, not from the client. If accountNo came from a query or body sent by the browser, an attacker could log in with account A and then claim account B's accountNo to bypass layer 3.
// Callback excerpt: check the account type before persisting the session
const accountNo = idTokenClaims['https://claims.example.com/account_no'];
if (!accountNo) throw new LoginFailed('missing account_no claim');

const attr = await accountAttributeApi.get(accountNo);   // retries 2 times internally
if (attr.accountType !== 'online-trading') {
  await redis.del(`login:${sessionId1}`);
  return redirectTo(FAILURE_SCREEN);                    // no Set-Cookie
}

5. Post-login processing: block or skip?

Once the account type is valid, MemberPortal calls two more internal APIs. They differ in nature, and the spec must state that difference clearly.

APIPurposeWhat happens on error?Classification
Login Status APIReturns isLoginAllowed, needsTradingInfoEntryError → delete SessionID1, do not persist SessionID2 (it does not exist yet), do not set cookies, error screen. isLoginAllowed=false → "Login failed"Login-blocking
Login History APIRecords login history with usedPasskeyError → ignore, login still succeedsBest-effort
LoginStatusAPI├─networkerror/5xx(afterretry)──▶stop,nosessionissued┐├─isLoginAllowed=false─────────────▶stop,"Loginfailed"│BLOCKINGgroup└─OK┘│├─needsTradingInfoEntry=true──▶skipLoginHistory(userhasnotenteredtradinginfoyet)└─needsTradingInfoEntry=false──▶callLoginHistoryAPI(usedPasskey)├─error→logwarning,CONTINUE┐BEST-EFFORTgroup└─OK┘

Why is Login History best-effort?

Login history is valuable for operations and audit, but it does not decide whether the user may use the system. If a supporting API's outage prevents every customer from logging in, that is a design flaw: a non-essential dependency has become a single point of failure.

However, "fire-and-forget" must be a deliberate, documented decision, because it has consequences: the history may be incomplete, and the audit team needs to know that. The spec should have a line like: "Login History API errors do not block login; the BFF writes a warning log with an internal error code for later reconciliation."

How to write it in the spec

A concise way to present it is to add an "Impact on error" column to the table of APIs being called:

StepAPIRetryImpact on errorSession deletedSet cookie?Screen
5Account Attribute2BlockingSessionID1NoSystem error / Login failed
6Login Status2BlockingSessionID1NoSystem error / Login failed
8Login History0Non-blockingNoneYessuccessUrl

This table answers all three questions of every login spec (Day 1, Part 1) for each branch.

6. When the layers return conflicting results

The three layers use data from different sources, so they can diverge:

ScenarioLayer 1 (IdP)Layer 3 (BFF)ResultWho handles it?
Account type just changed, IdP has stale cacheAllowRejectLogin fails at the BFFWorking as designed: layer 3 decides
IdP script misconfigured, allows every typeAllowRejectLogin fails at the BFFLayer 3 saves the day; alert when layer 3's rejection rate rises abnormally
Account Attribute API returns the wrong typeRejectAllowUser is blocked at the IdP, never reaches layer 3Layer 1 saves the day
App SSO channelNot traversedRejectLayer 3 is the only layerThe Day 6, Part 1 spec must call the Account Attribute API

Lesson: layer 3 must always run for every channel, and there should be a metric counting layer 3 rejections to detect when layer 1 or the data is wrong.

7. Common mistakes

MistakeWhy it is dangerous
Setting cookies first, then calling the Account Attribute API and deleting on errorThere is a window where a session is live for an invalid account; if the BFF crashes midway, the session survives until its TTL expires
Taking accountNo from a request parameterBypasses layer 3 by claiming someone else's accountNo
Treating Login History as blockingA supporting API outage prevents every customer from logging in
Treating Login Status as best-effortLocked accounts can still log in when the API fails
No retry for blocking APIsA transient network error turns into mass "Login failed"
Error message saying "your account is type X"Leaks the account type to someone who does not own the account

Part 3: Backup IdP and Health Check

1. Why do we need a backup IdP?

All of MemberPortal's Web logins go through Auth0. If Auth0 has an incident (regional outage, maintenance, tenant misconfiguration), no customer can log in, even though the core system is running normally. For a securities firm, a few hours of being unable to place orders during trading hours is a major loss and may breach obligations to the regulator.

Solution: run a Keycloak operated by ACME in parallel, configured with the same user store (via user federation to the customer data source), the same portal-web client, and the same custom claims. When Auth0 is unhealthy, the BFF redirects users to Keycloak.

┌──────────────┐┌──healthy──▶│Auth0│(primaryIdP)│└──────────────┘/auth/web/login──selectIdP│┌──────────────┐└─unhealthy─▶│Keycloak│(backupIdP,ALT_IDP_ENABLED=true)└──────────────┘

Prerequisite for failover to be meaningful: both IdPs must issue id_tokens with the same claims structure that the BFF callback needs (sub, account_no, connection, nonce, auth_time). Otherwise the callback has to branch by IdP, which increases the error surface.

2. The IdP selection step in /auth/web/login

This step runs before the BFF generates state/nonce/code_verifier and redirects, because the /authorize URL, client_id, and redirect_uri differ between the two IdPs.

ReceiveGET/auth/web/login?successUrl=...│├─ALT_IDP_ENABLED=false──────────────────────────────▶idProvider="auth0"│└─ALT_IDP_ENABLED=true│├─Healthcachestillvalid(≤AUTH_HEALTH_CACHE_SECONDS=60s)?│└─yes→usethecachedvalue│└─expired→callAuthHealthAPI├─200{healthy:true}→idProvider="auth0",cache60s├─200{healthy:false}→idProvider="keycloak",cache60s└─error/timeout→idProvider="auth0"(FAIL-OPEN),cache60s│▼Generatestate,nonce,code_verifierStorelogin:{id}={state,nonce,codeVerifier,successUrl,idProvider,channel:"Web"}302→{authorizeUrlofidProvider}?client_id=...&code_challenge=...

Why a separate ALT_IDP_ENABLED flag in addition to the health check?

Because the backup Keycloak may not be ready in some environments (users not yet synced, client not yet configured), or the operations team may want to disable failover during Keycloak maintenance. This flag lets you "switch it off entirely" without touching the Auth Health API. In the spec, these two conditions are two separate lines, not merged.

What is the Auth Health API?

An internal core system API that returns { healthy: true | false } for the primary IdP. It can be based on automated monitoring (synthetic login), or on a manual switch that the operations team flips when they confirm Auth0 has an incident. The second approach is more common in practice because it avoids mistaken failover caused by a transient error. The spec does not need to define how the API decides, but it must clearly state the contract: input, output, timeout, and behavior on error.

3. Why cache the health check?

/auth/web/login is called every time someone wants to log in. If every call hit the Auth Health API:

ProblemConsequence
Load on the core system grows in proportion to the number of loginsLoad peaks exactly during an incident (many people retrying login)
Every login gets an extra round-trip of latencyPoor experience
The result may flap between true/false constantly if monitoring is noisyUser A goes to Auth0, user B right after goes to Keycloak, hard to diagnose

A 60-second cache (AUTH_HEALTH_CACHE_SECONDS) solves all three: at most one call per minute per BFF instance, and a stable state within a short window. Trade-off: when Auth0 breaks, for up to 60 seconds users are still sent to Auth0 and fail. The number 60 is a balance between "react quickly" and "stay stable", and the reason must be written in the spec so that later maintainers do not change it arbitrarily.

// Simplified example: per-instance health cache
class IdpSelector {
  private cached?: { healthy: boolean; expiresAt: number };

  async select(): Promise<'auth0' | 'keycloak'> {
    if (process.env.ALT_IDP_ENABLED !== 'true') return 'auth0';

    const now = Date.now();
    if (this.cached && now < this.cached.expiresAt) {
      return this.cached.healthy ? 'auth0' : 'keycloak';
    }

    let healthy = true;                      // fail-open by default
    try {
      const res = await authHealthApi.get({ timeout: 2000 });
      healthy = res.healthy === true;
    } catch (e) {
      logger.warn({ code: 'AUTH_HEALTH_UNAVAILABLE' }, 'health api error, assume healthy');
    }

    const ttl = Number(process.env.AUTH_HEALTH_CACHE_SECONDS ?? 60) * 1000;
    this.cached = { healthy, expiresAt: now + ttl };
    return healthy ? 'auth0' : 'keycloak';
  }
}

Note that the cache is per BFF instance. With multiple instances, each may differ from the others by up to 60 seconds. For failover purposes this drift is acceptable; if you need absolute consistency, you can cache in Redis, but then Redis becomes a dependency of the IdP selection step as well.

4. Storing idProvider in SessionID1

The /auth/web/login-callback callback receives a code and must exchange it at the token endpoint of the same IdP that issued it. If the user started at Keycloak but by callback time health has recovered and the BFF picks Auth0, calling Auth0's /oauth/token with a Keycloak code will fail.

That is why idProvider is pinned at the moment login starts and stored in login:{id} together with state, nonce, and code_verifier. The callback reads it from SessionID1 and does not call the health check again.

Field in login:{id}SourceUsed in the callback to
stateCSPRNGMatch state from the query
nonceCSPRNGMatch the nonce claim in the id_token
codeVerifierCSPRNGSend with /oauth/token (PKCE)
successUrlQuery of /auth/web/login (validated)Redirect after login completes
idProviderIdP selection resultChoose the token endpoint, client_id/secret, JWKS, expected iss
channelConstant WebWrite into SessionID2
Callbackreceivescode+state├─Readlogin:{id}bytheSessionID1cookie├─idProvider="keycloak"→tokenUrl=KEYCLOAK_TOKEN_URL,jwks=jwksKeycloak,iss=KEYCLOAK_ISSUER└─idProvider="auth0"→tokenUrl=AUTH0_TOKEN_URL,jwks=jwksAuth0,iss=AUTH0_ISSUER

The id_token verify step (Day 3, Part 3) therefore also depends on idProvider: the expected iss and the JWKS key set differ. If the wrong JWKS is used, the signature will not match and login fails; if iss is not checked per IdP, an id_token from one IdP could be accepted in the other IdP's flow.

5. Preparing JWKS for both IdPs at startup

Day 4, Part 1 explained that the BFF obtains the Management API token at boot. At the same time, when ALT_IDP_ENABLED = true, the BFF downloads and caches the JWKS of both Auth0 and Keycloak.

BFFstartup├─ObtainManagementAPItoken(client_credentials,client`portal-management`)├─DownloadAuth0JWKS→cachebykid└─ALT_IDP_ENABLED=true→DownloadKeycloakJWKS→cachebykid└─downloaderror→retry2times→stillfailing→logerror,BFFstillstarts(thecallbackwillreloadlazilywhenitmeetsakidnotinthecache)

Why preload instead of loading on demand?

  • Failover time is when infrastructure is unstable; the fewer network calls in the callback, the better.
  • If the Keycloak JWKS were only loaded when the first user goes through Keycloak, that user would bear the extra latency and the risk of a load failure.

The JWKS cache still needs a refresh mechanism when it encounters an unknown kid (key rotation), as learned in Day 3, Part 3; failover does not change that principle.

6. The fail-open decision: when the Auth Health API itself fails

This is the most debatable point of the lesson. When the Auth Health API does not respond, the BFF has two options:

OptionBehaviorProsCons
Fail-open (MemberPortal's choice)Treat Auth0 as healthy, go to Auth0A supporting API's outage does not trigger a mass IdP switch; the default behavior is the normal behaviorIf Auth0 and the Health API fail together (e.g., the same network outage), users are still sent to a broken Auth0
Fail-closed to KeycloakTreat Auth0 as unhealthy, go to KeycloakNo dependency on Auth0 when unsureA small Health API glitch moves every customer to another IdP, possibly causing a bigger incident than the one it was meant to prevent
Reject loginReturn a system errorSafest in terms of logicCreates downtime on its own from a monitoring API

Why fail-open was chosen: the Auth Health API is a supporting tool, not the source of truth about Auth0. When a supporting tool breaks, falling back to the default behavior is the least surprising. The backup Keycloak can still be activated by fixing the Health API or via the manual switch.

Mandatory in the spec: state clearly that this is a deliberate fail-open, together with the conditions and how it is monitored. For example:

When the Auth Health API fails or times out (2 seconds), the BFF treats the primary IdP as healthy and writes a warning log with code AUTH_HEALTH_UNAVAILABLE. This result is cached for 60 seconds like a normal result. The operations team must alert when this code appears continuously for more than 5 minutes.

If it is not stated, later reviewers will treat it as an oversight (and they are right to be suspicious, because fail-open elsewhere, such as in signature verification, is a serious vulnerability). Item 7 of the Day 7, Part 3 checklist exists precisely to catch undeclared fail-open points.

7. Other points to review when adding a backup IdP

ItemQuestion the spec must answer
Client in KeycloakDoes portal-web have the same redirect URI allow-list (login-callback, logout-callback)?
Custom claimsDoes Keycloak have a protocol mapper issuing account_no and connection in the same namespace?
LogoutRP-initiated logout goes to Keycloak's end_session if the session was created via Keycloak → does SessionID2 need to store idProvider?
Step-up (Day 7, Part 1)Do the step-up clients have Keycloak versions, or is step-up paused during failover?
PasskeyDoes Keycloak support an equivalent passkey? If not, usedPasskey is always false via Keycloak
Allow matrix (Day 6, Part 2 layer 1)Does Keycloak enforce the client × account type matrix? If not, layer 3 at the BFF is the only layer
MonitoringLogin count metric per IdP, alert when Keycloak has traffic outside maintenance windows

The "Logout" row shows a consequence that is often forgotten: if logout must call the same IdP used for login, then idProvider must live through SessionID2 as well, not just SessionID1. This is a decision the spec must lock in.


Review Questions

  1. Why does MemberPortal use the same SessionID2 and xsrfToken for all three channels instead of separating them?

    Show answer

    Because the session check part (the /api/s/* middleware) is the most frequently called part and needs to be the simplest. With three kinds of session, every middleware and every API proxy would have to branch by channel, which is easy to get wrong and hard to test. Instead, the project pushes all differences into the issuing step: OIDC for Web, opaque token verify for App, Operator login for Operator. The end result of all three is a sess:{id} record with the same structure, differing only in the channel value.

  2. Why does /auth/app/login return 403 rather than 401 when the token is invalid?

    Show answer

    Because 401 in MemberPortal means "no valid session yet, go log in", and the UI interceptor handles 401 by... calling /auth/app/login again. If this endpoint also returned 401 on failure, the UI would fall into a loop. 403 means "we have identified you but you are not allowed": bad token, expired, or invalid account type. When the UI gets a 403 it stops and shows "Login failed", without trying again.

  3. The UA can be spoofed. So what is the point of the BFF checking the UA in /auth/app/login?

    Show answer

    It is a routing step, not an authorization barrier. Checking the UA keeps regular browsers from calling the endpoint by mistake, reduces pointless verify API calls, and makes logs easier to classify. But access is granted entirely based on (1) APP_SSO_TOKEN being successfully verified via the SSO Token Verify API and (2) the correct account type. An attacker who spoofs the UA without a token still gets 403. The spec must state this clearly so reviewers do not mistake the UA for a security layer.

  4. Compare the risk of APP_SSO_TOKEN leaking with the risk of an id_token leaking.

    Show answer

    APP_SSO_TOKEN is an opaque handle: whoever holds it and calls /auth/app/login correctly (with a spoofed UA) is issued a session until the token expires or is revoked by the core system. On the other hand, revocation is immediate because every use goes through the verify API. If an id_token leaks, the attacker can read the claims, but to reuse it at the BFF callback they would also need to match the nonce with SessionID1 and the aud of the right client, so reusability is low; conversely, an id_token cannot be revoked before exp. The two models have different risk profiles; the spec should choose a short TTL for the opaque token and protect the cookie with Secure.

  5. List what the UI must clear and must not clear when receiving a 401 in the app's WebView.

    Show answer

    Must clear: cookies sid, xsrf, uid (and sid_stepup if present), and all session-related sessionStorage. Must not clear: APP_SSO_TOKEN, because this cookie is set by the native app and is the only means to SSO again. If it is cleared, the next 401 will call /auth/app/login without a token → 403 → the user is stuck at "Login failed" even though the app is still logged in. The spec should write this as a table of "which cookie, cleared when, by whom".

  6. Why is the application-level control (only showing the button to valid accounts) not counted as a security layer?

    Show answer

    Because it runs on the client, entirely in the user's hands. Anyone can type the URL https://portal.example.com/... directly, modify the JavaScript, or call the API with another tool. Hiding the button only improves the experience and reduces pointless calls. Every "let in or not" decision must be enforced on the server (IdP or BFF), where the user has no control.

  7. If you could keep only one of the three layers, which would you keep? Why?

    Show answer

    Keep layer 3 (BFF calls the Account Attribute API). It is the only layer that every channel goes through: Web via the OIDC callback, App via /auth/app/login, Operator via its dedicated endpoint. Layer 1 at the IdP is bypassed by the app SSO channel and depends on configuration outside the BFF. Layer 3 also uses data directly from the core system, which is the source of truth for the account type.

  8. Why is SessionID2 written to Redis only after the Account Attribute API and the Login Status API have passed?

    Show answer

    So that there is never a valid session in Redis for an account that has not been confirmed. Writing first and deleting on error carries two risks: (1) a short window in which the session is live and could be used if the cookie was already set; (2) if the BFF crashes or loses its Redis connection between the write and the delete, an "orphan" session lives until its 3-hour TTL expires. Principle: check everything, then persist once.

  9. Distinguish "login-blocking" APIs from "best-effort" APIs. Give an example of each in MemberPortal and how the spec should express it.

    Show answer

    A login-blocking API is one whose result decides whether the user is issued a session; on error, stop and do not set cookies. Examples: Account Attribute API, Login Status API. A best-effort API has supporting value (audit, statistics); on error, log and continue. Example: Login History API. The spec should have a table with the columns "Impact on error", "Session deleted", "Set cookie?", "Screen", plus a sentence stating that ignoring the error is deliberate, along with how to reconcile (logs with an internal error code).

  10. Which control layer did adding the app SSO channel open a hole in? What is the general lesson?

Show answer

It bypasses layer 1 at the IdP, because the SSO token is verified by the core system, not via Auth0, so the post-login Action does not run. If the old design implicitly relied on layer 1 being enough, the new channel would let every account type that has the app get in. Lesson: every time you add a new channel or IdP, re-examine each existing control layer and ask "does the new channel go through this layer?". This is item 6 in the review checklist in Day 7, Part 3.

  1. Why must idProvider be stored in SessionID1 instead of calling the health check again at the callback?
Show answer

Because a code issued by an IdP can only be exchanged at that IdP's token endpoint, with the corresponding client_id/client_secret and redirect_uri; the returned id_token can also only be verified with that IdP's JWKS and iss. If the callback decided again on its own, the health result might have changed in the few seconds between the two steps, leading to the code being exchanged at the wrong place. Pinning idProvider at the start and carrying it in login:{id} keeps a single login attempt consistent from beginning to end.

  1. What risk does the 60-second health cache create, and why is it still accepted?
Show answer

Risk: when Auth0 has just broken, for up to 60 seconds users are still sent to Auth0 and fail; conversely, when Auth0 recovers, for up to 60 seconds users still go to Keycloak. It is accepted because: (1) it avoids calling the Auth Health API on every login, especially since an incident is exactly when logins spike; (2) it avoids a flapping state in which consecutive users go to two different IdPs; (3) 60 seconds is small compared to the duration of a typical IdP incident. This number must be written in the spec together with its rationale.

  1. Explain the fail-open decision when the Auth Health API fails. How does it differ from fail-open in signature verification?
Show answer

Fail-open here means "if unsure, treat the primary IdP as healthy and take the default route". It does not lower security: the user still has to authenticate fully at Auth0, and may simply fail if Auth0 is also broken. In contrast, fail-open in signature verification ("if JWKS cannot be loaded, skip verification") drops a security check, allowing forged id_tokens to be accepted. Principle: fail-open is only acceptable for routing/availability decisions, never for authentication/authorization decisions, and it must always be declared clearly in the spec along with monitoring.

  1. Why load the Keycloak JWKS at startup even though it may go unused for months?
Show answer

Because the moment Keycloak is needed is the moment infrastructure is unstable; every extra network call in the callback increases the chance of failure exactly when it matters most. Preloading at boot means a callback via Keycloak needs only a single call (the token endpoint). Cost: one request at startup and a little memory. A reload mechanism for unknown kid values is still needed to handle Keycloak's key rotation.

  1. List three items, beyond the IdP selection step, that must be reviewed when enabling the backup IdP.
Show answer

For example: (1) Logout: RP-initiated logout must call Keycloak's end_session if the session was created via Keycloak, so idProvider may also need to be stored in SessionID2; (2) Custom claims: Keycloak must issue account_no and connection in the same namespace so the callback does not branch; (3) Allow matrix (layer 1 at the IdP): if Keycloak does not enforce it, layer 3 at the BFF is the only layer and must be guaranteed to run; in addition there are the step-up clients, passkey, the redirect URI allow-list, and traffic monitoring per IdP.

Hands-on Exercises

Exercise 1

Draw a Mermaid sequence diagram for the app SSO flow from the moment the WebView opens until the original request is successfully retried, including the 403 branch.

Expected output: a diagram with all 4 participants (App, WebView, BFF, Core system), clearly marking where sess:{id} is created and where cookies are set.

Exercise 2

Write a data model table for sess:{id} when channel = App: each field, its data source (from the verify API, from the Account Attribute API, generated by CSPRNG, constant), and the TTL.

Expected output: a 6-7 row table in which no cell in the "Source" column says "from the client".

Exercise 3

Scenario analysis : an old version of ACME Trade App sends the UA ACMETrade/1.0 (which does not match the new pattern). What will users on the old version experience? Propose how to handle it in the spec (a UA pattern accepting multiple versions? an app update notice?).

Expected output: 1 paragraph of analysis + 1 decision with its rationale.

Exercise 4

Write test cases for /auth/app/login: at least 8 cases (wrong UA, missing cookie, malformed cookie, verify API 5xx ×3, expired token, wrong accountType, Login Status not allowed, happy path).

Expected output: a table of case → input → status code → whether a session is created.

Exercise 5

Redraw the callback flow from the "verify id_token OK" step to "302 successUrl" as a Mermaid flowchart, including all error branches of the Account Attribute API, Login Status API, and Login History API.

Expected output: each branch ends with an explicit note (which session is deleted / set cookie? / screen).

Exercise 6

Write an "Impact on error" table for the app SSO channel (/auth/app/login), and compare it with the Web channel table in section 5.

Expected output: point out the differences (status codes instead of redirects) and the similarities (check first, persist later).

Exercise 7

Scenario analysis : the operations team proposes "when the Login Status API fails, just allow login so customers are not affected". Write 1 paragraph rebutting this based on the blocking/best-effort distinction, and propose alternatives (retry, circuit breaker, maintenance notice).

Expected output: a decision with its rationale, not just "no".

Exercise 8

Design metrics : propose 3 metrics/alerts to detect a misconfigured layer 1 based on the behavior of layer 3.

Expected output: metric name, alert condition, action when the alert fires.

Exercise 9

Write a decision table for the IdP selection step covering all combinations: ALT_IDP_ENABLED (true/false) × cache state (valid/expired) × Health API result (true/false/error).

Expected output: an 8-10 row table, each row stating idProvider and whether the cache is updated.

Exercise 10

Extend the data model : propose adding idProvider to sess:{id} so that logout calls the right IdP. Rewrite the SessionID2 data model table and describe the changes to /auth/web/logout.

Expected output: a table + 5-8 bullets describing the processing branches.

Exercise 11

Write a spec paragraph for the fail-open behavior of the Auth Health API following the template in section 6, including the log code and alert condition. Then write a fail-closed version and compare the consequences in 2 scenarios: (a) the Health API fails for 5 minutes while Auth0 is normal; (b) Auth0 and the Health API fail together.

Expected output: 2 spec paragraphs + a table comparing the 2 scenarios.

Exercise 12

Mermaid sequence diagram for the login flow via Keycloak during failover, marking where idProvider is read from login:{id} and where the JWKS is selected.

Expected output: a diagram that matches 1-to-1 the IdP selection step in section 2 and the callback in section 4.

References


Next lesson →