This lesson combines 3 topics: Session model: server-side sessions and the two kinds of session in one login flow, CSRF and the synchronizer token in a BFF, Logout, 401 handling and the session lifecycle.
Learning Objectives
- Compare server-side sessions (Redis) with token-based sessions (JWT on the client), and explain why MemberPortal chose sessions
- Generate a Session ID correctly with a CSPRNG, and know why
Math.random()is a security bug - Distinguish SessionID1 (login sequence) from SessionID2 (logged in): why they are separate, how long each lives, when each is deleted
- Distinguish absolute and sliding TTL, and TTL in Redis versus on the cookie
- Write the session data model table in a spec: key, field, data source, TTL
- Explain CSRF with a concrete scenario on MemberPortal and identify the conditions an attack needs to succeed
- Understand why
SameSite=Laxis not enough to consider CSRF handled - Understand the synchronizer token mechanism: token stored in the session, client sends it back in the
X-XSRF-TOKENheader, middleware compares them - Compare the synchronizer token with the double-submit cookie and origin checks
- Write a sample NestJS middleware and the spec section for the "common session check" of
/api/s/* - Describe fully what logout deletes in Redis, in cookies, and at the IdP
- Write the UI-side 401 handling procedure: what to delete, what to keep, where to go next; why
APP_SSO_TOKENis not deleted - Understand session fixation and why SessionID2 must be a new id after authentication
- Analyze what an attacker can do with each cookie: only
uid, onlysid, bothsid+xsrf - Draw the full lifecycle diagram of a session from creation to death along every path
Part 1: Session model: server-side sessions and the two kinds of session in one login flow
1. Server-side session vs JWT on the client
Day 1, Part 1 framed the question "who holds the token". Today we go deeper into "how it is held".
| Criterion | Server-side session | JWT on the client |
|---|---|---|
| Session data lives in | Redis; the browser only has the id | The token; the browser holds all of it |
| Immediate revoke | DEL sess:{id} | No, you must wait for exp or build a denylist (which is state again) |
Changing session data (e.g. usedPasskey) | Write to Redis, effective immediately | Must issue a new token |
| Cost per request | 1 Redis read | 0 I/O, only CPU for verification |
| Horizontal scaling | Needs a shared Redis | Stateless, easy |
| Exposure through XSS | Only the id leaks (if not HttpOnly); data stays on the server | All claims and a usable token leak |
| Good fit for | Fintech, where accounts must be locked immediately | Public APIs, internal microservices |
MemberPortal chose server-side sessions because of the business requirements "account lock takes effect immediately" and "IdP tokens never leave the server". The access_token/id_token received from the IdP is used and then discarded (or stored in Redis when needed to call the MFA API), and is never sent down to the browser.
Note the distinction: MemberPortal still uses JWT, but it is the id_token issued by the IdP and verified by the BFF on the server (Day 3, Part 3). What it does not do is issue a JWT for the browser to hold.
2. Session ID: how to generate it correctly
A Session ID is a shared secret between the browser and the BFF. Whoever can guess the id can take over the session. Three requirements:
- Unguessable: from a CSPRNG, not from
Math.random(), not from a timestamp/counter. - Enough entropy: OWASP recommends ≥ 64 bits; in practice use 32 bytes (256 bits) so you never have to think about it.
- Meaningless: do not embed accountNo, time, or any other data.
import { randomBytes } from 'node:crypto';
/** Generate a secure random string, base64url, no padding. */
export function secureRandomString(byteLength = 32): string {
return randomBytes(byteLength).toString('base64url');
}
// example: "UUgnOKzDSKNQnUXd-Rp_CPbOsJywOijb9j0wNMzo0Ac" (43 characters for 32 bytes)
2.1 Why Math.random() is a vulnerability
Math.random() in V8 uses xorshift128+, which is not a CSPRNG: observing a few consecutive outputs is enough to reconstruct its state and predict the next values. With session ids, an attacker creates a few sessions of their own, observes the ids, and then computes the id of a victim created right afterwards. crypto.randomBytes draws from the operating system's entropy source and does not have this flaw.
2.2 This function is a "common process"
The same secureRandomString function is used for: SessionID1, SessionID2, xsrfToken, state, nonce, code_verifier. The spec moves this function into the Common Processes file and every endpoint just links to it instead of describing it again. Benefit: fix it in one place, and reviewers do not have to inspect 6 places for a stray Math.random().
3. Two kinds of session in one login flow
This is the most important design point of the lesson. One OIDC login needs to store two groups of data of a different nature:
| SessionID1: login sequence | SessionID2: logged in | |
|---|---|---|
| Redis key | login:{id} | sess:{id} |
| Created at | GET /auth/web/login (before redirecting to the IdP) | GET /auth/web/login-callback after verification |
| Stores | state, nonce, codeVerifier, successUrl, failureUrl, idProvider, channel | accountNo, sub, xsrfToken, channel, usedPasskey |
| Nature of the data | Temporary, only meaningful for a few minutes between the outbound redirect and the callback | Durable, represents the authenticated user |
| Cookie | login_sid: temporary cookie for the login sequence (HttpOnly, Lax) | sid |
| TTL | SESSION_LOGIN_TTL (e.g. 3h, so the user has time to enter a password, do MFA, reset a forgotten password) | SESSION_TTL (e.g. 3h) |
| Deleted when | The callback finishes, whether it succeeds or fails | Logout, TTL expiry, BFF detects an invalid account |
3.1 Why not use one session for both?
- Different lifecycles. state/nonce/code_verifier must die right after the callback (reusing them is a replay vulnerability). accountNo/xsrfToken must live for 3 hours. Combining them means either deleting fields one by one (easy to forget) or letting temporary data live alongside the real session.
- Preventing session fixation. If an attacker forces the victim to use a SessionID1 the attacker already knows (e.g. through a link containing the id), and the victim then logs in successfully without the id changing, the attacker now owns a logged-in session. Creating a brand-new SessionID2 after authentication cuts off this scenario. Details in Day 2, Part 3.
- Clear read/write ownership. The session middleware for
/api/s/*only readssess:*and never toucheslogin:*. The callback endpoint only readslogin:*and then createssess:*. No key is ever read and written across two flows. - Multiple parallel login sequences do not corrupt data. A user opens 2 login tabs, creating 2 independent
login:*keys in Redis; Redis does not overwrite them. But both tabs share onelogin_sidcookie, so the later tab overwrites the earlier tab's cookie; when the earlier tab's callback returns, it reads the later tab'slogin:*and fails at the state comparison (see Day 1, Part 2, the redirect chain section). That is the desired behavior: one cookie points to exactly one sequence, and two sequences never mix their data.
3.2 Self-check question
If the callback fails because the state is wrong but you forget to delete SessionID1, what happens? Hint: an attacker holding the victim's temporary cookie can attempt the callback many times with different code values for 3 hours; the nonce/code_verifier are still there to match against. Deleting immediately = each login sequence gets exactly one callback attempt.
4. TTL: absolute vs sliding, Redis vs cookie
4.1 Absolute vs sliding
| Type | Behavior | Redis | Used for |
|---|---|---|---|
| Absolute | Expires exactly N seconds after creation, regardless of activity | SET key val EX 10800 once | Login sequence, step-up (fixed 600s), the logged-in session if the policy is "force login again after 3h" |
| Sliding | Each use extends it by N seconds | EXPIRE key 10800 after each valid request | The logged-in session if the policy is "expires after 3h of inactivity" |
MemberPortal uses absolute for login:*, stepup:*, and absolute by default for sess:*. Why absolute for the logged-in session in fintech: it puts a hard limit on how long a hijacked session can live, and it simplifies auditing ("this session was created at X, it is guaranteed dead at X+3h"). Sliding is convenient for users but needs an extra absolute cap (e.g. 12h max), otherwise a session can live forever.
The spec must state the TTL type explicitly, because both types can be written as "TTL 3h" yet behave completely differently.
4.2 MemberPortal's four TTLs
| Env var | Applies to | Example value | Type | Notes |
|---|---|---|---|---|
SESSION_LOGIN_TTL | login:* | 3h | absolute | Long because the user may need to reset a password or do MFA at the IdP |
SESSION_TTL | sess:*, mock:* when MOCK_SESSION_TTL is not set | 3h | absolute | Security policy; changing it needs approval |
STEPUP_SESSION_TTL | stepup:* | 600s | absolute, fixed | Proof of "just re-authenticated", must be short |
MOCK_SESSION_TTL | mock:* | 3600s (1h) in dev | absolute | Exists only in the test stage |
stepup-mfa:* alone has no env var: TTL = expires_in of the access_token received from the IdP, because this session holds a real access_token to call the MFA API; once the token expires the session is meaningless. Details in Day 7, Part 1.
4.3 Redis TTL vs cookie TTL
As covered in Day 1, Part 3: cookies do not set Expires, and Redis is the source of truth. Consequence for the spec: every "session expired" statement means "the Redis key no longer exists", and the behavior is 401 → UI deletes cookies. There is no "cookie expired" branch in the BFF spec.
5. Session data model in the spec
A good session table answers, for each field: name, type, where it comes from, whether it is required. The "Source" column is the one most often left out, and also the one that catches the most bugs.
5.1 SessionID1: login:{id}
| Field | Type | Source | Required | Notes |
|---|---|---|---|---|
state | string | Generated with secureRandomString() at /auth/web/login | ✔ | Compared with the state query at the callback |
nonce | string | Generated with secureRandomString() | ✔ | Compared with the nonce claim in the id_token |
codeVerifier | string | Generated with secureRandomString(32) | ✔ | Sent to /oauth/token; code_challenge = BASE64URL(SHA256(verifier)) |
successUrl | string | The successUrl query after normalization (Day 1, Part 2 section 4) | ✔ | Do not store the raw value |
failureUrl | string | The failureUrl query after normalization | ✘ | Defaults to the portal's error screen |
trackingParam | string | The _gl query, ≤ 512 characters | ✘ | Appended to successUrl on redirect |
idProvider | auth0 | keycloak | Result of IdP selection (health check + ALT_IDP_ENABLED) at login time (Day 6, Part 3) | ✔ | The callback uses it to know which token endpoint to call |
channel | Web | App | Operator | Fixed by the creating endpoint | ✔ | /auth/web/login → Web |
| TTL | — | SESSION_LOGIN_TTL, absolute | — |
5.2 SessionID2: sess:{id}
| Field | Type | Source | Required | Notes |
|---|---|---|---|---|
accountNo | string | Claim https://claims.example.com/account_no in the verified id_token | ✔ | Never taken from client-sent query/body/cookie |
sub | string | Claim sub in the id_token | ✔ | Also written to the uid cookie |
xsrfToken | string | Generated with secureRandomString() when the session is created | ✔ | Written to the xsrf cookie; compared with the X-XSRF-TOKEN header |
channel | Web | App | Operator | Copied from SessionID1 (web) or fixed by endpoint (/auth/app/login → App) | ✔ | Native step-up only accepts App |
usedPasskey | boolean | From the id_token's connection claim (web) or passkeyFlag from the SSO Token Verify API (app) | ✔ | Decides the client step-up (Day 7, Part 1) |
idProvider | auth0 | keycloak | null | Copied from SessionID1 (Web channel) | ✘ | Lets logout know which IdP's end-session to call. null for App/Operator/mock channel sessions (which do not go through an IdP) → logout skips the IdP step (Day 2, Part 3) |
| TTL | — | SESSION_TTL, absolute | — |
5.3 Why the "Source" column matters
The accountNo row is the textbook example. If the spec only says "accountNo: account number", a developer building a new endpoint might take it from the request body "for convenience". Then a client can claim someone else's accountNo and the BFF proxies to the API Gateway with a forged accountNo. Writing the source explicitly as "claim in the verified id_token" closes this door at the spec level. When reviewing a new endpoint of the same kind, the first thing to do is compare the Source column with the sibling endpoints that already exist.
6. Redis operations and how to write them in the spec
// Create SessionID1
const loginId = secureRandomString();
await redis.set(`login:${loginId}`, JSON.stringify(loginData), 'EX', SESSION_LOGIN_TTL);
// Callback: read and delete immediately, regardless of outcome
const raw = await redis.getdel(`login:${loginId}`); // Redis ≥ 6.2: atomic read + delete
if (!raw) return redirectToLoginFailed();
const login = JSON.parse(raw);
// ... verify state, exchange code, verify id_token ...
// Success: new SessionID2
const sid = secureRandomString();
await redis.set(`sess:${sid}`, JSON.stringify(sessData), 'EX', SESSION_TTL);
GETDEL neatly satisfies the requirement "each login sequence can only be called back once": it reads and deletes in one command, so if two callbacks run in parallel with the same temporary cookie, only one of them gets the data.
In the spec, describe it in natural language but keep it atomic: "Read and delete SessionID1 in a single operation. If it does not exist → Login failed."
Part 2: CSRF and the synchronizer token in a BFF
1. What CSRF is, by example
Cross-Site Request Forgery: the attacker makes the victim's browser send a request to portal.example.com with the victim's session cookie, without the victim knowing.
Three conditions for CSRF to succeed:
- The server relies only on the cookie to authenticate the request.
- The browser sends the cookie automatically with that cross-site request.
- The attacker knows the request structure in advance (URL, parameters), without needing the cookie value.
Preventing CSRF means breaking at least one condition. Condition 3 cannot be broken (the API is a public contract). That leaves 1 and 2.
2. Breaking condition 2: SameSite, and why it is not enough
SameSite=Lax (Day 1, Part 3) stops the browser from sending cookies on cross-site POSTs → the form above fails. So why do we still need more?
| Scenario | Does Lax block it? |
|---|---|
| Form POST from evil.net | ✔ Blocked |
<img src="https://portal.example.com/api/s/delete?id=1"> (GET with side effects) | ✔ Blocked: <img> is a subresource, not a top-level navigation |
Link <a href="https://portal.example.com/api/s/delete?id=1"> that the user clicks | ✘ Not blocked: top-level GET navigation |
| Old browser without SameSite support | ✘ Not blocked |
| Cookie without a declared SameSite, set < 2 minutes ago, Chromium allows cross-site POST ("Lax + POST" of Lax-by-default) | ✘ Not blocked, but only when the attribute is missing; MemberPortal declares SameSite=Lax explicitly, so this does not apply |
A compromised subdomain (blog.example.com with XSS) sends requests to the portal | ✘ Not blocked: same site |
Conclusion for the spec: SameSite is defense in depth, not the primary mechanism. The primary mechanism must break condition 1: the server requires something the cookie cannot carry.
In addition: every /api/s/* API with side effects must be POST/PUT/DELETE, never GET. This rule eliminates the "GET link" row in the table as well.
3. Breaking condition 1: the synchronizer token
3.1 The idea
The server generates a random token bound to the session and stores it in the session. The client must send that token back somewhere other than a cookie (a header). A cross-site page can make the browser send cookies, but cannot read the token to put it in the header → the request has a missing/wrong token → rejected.
Login callback succeeds
BFF: xsrfToken = secureRandomString()
sess:S2 = {..., xsrfToken: X2}
Set-Cookie: sid=S2; HttpOnly
Set-Cookie: xsrf=X2 ← NOT HttpOnly so JS can read it
Every /api/s/* request
UI (same origin): token = read cookie xsrf
fetch(url, { headers: { 'X-XSRF-TOKEN': token } })
Browser: attaches Cookie: sid=S2; xsrf=X2 automatically
BFF middleware: sess = GET sess:S2
sess.xsrfToken === header['x-xsrf-token'] ? continue : 401
evil.net page: browser attaches cookies (if SameSite allows)
but JS on evil.net cannot read the portal's cookies
→ no header → 401
3.2 Why compare against the session, not against the xsrf cookie?
There are two variants:
| Variant | What is compared | Needs server state? | Weakness |
|---|---|---|---|
| Synchronizer token (MemberPortal) | header vs sess.xsrfToken in Redis | Yes (Redis is already there) | No significant weakness once you have a session |
| Double-submit cookie | header vs xsrf cookie | No | If the attacker can set an xsrf cookie on the domain (via a compromised subdomain, or cookie tossing), it is bypassed |
Since MemberPortal already has server-side sessions, the synchronizer token is almost free and stronger. The xsrf cookie is only a transport channel for delivering the token to JS; the authoritative value lives in Redis. If an attacker overwrites the victim's xsrf cookie, the header will match the fake cookie but not Redis → 401.
3.3 Origin/Referer check
Checking that the Origin or Referer header matches https://portal.example.com is a third, cheap layer that should be enabled for state-changing requests. Do not use it as the only layer, because some proxies/privacy extensions strip the Referer, and Origin can be null in a few legitimate situations.
4. MemberPortal's XSRF middleware
4.1 Rules
- Applies to every request to
/api/s/*(including GET, for simplicity and so nothing is forgotten). - Does not apply to
/api/ns/*or/auth/*(auth endpoints have their own mechanisms: state for the callback, a guard for mock). - Missing
sidcookie, nonexistent session, missing header, mismatched header → the same 401 code and the same error body. Do not distinguish them, so as not to reveal "session exists but token is wrong" (which would tell an attacker they guessed the sid correctly). - Compare with a constant-time compare to avoid timing attacks.
4.2 Sample code
import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import { timingSafeEqual } from 'node:crypto';
import type { Request, Response, NextFunction } from 'express';
@Injectable()
export class SessionXsrfMiddleware implements NestMiddleware {
constructor(private readonly sessions: SessionStore) {}
async use(req: Request, _res: Response, next: NextFunction) {
const sid = req.cookies?.['sid'];
const headerToken = req.header('x-xsrf-token');
if (!sid || !headerToken) throw new UnauthorizedException({ bffErrCode: 'ERR_SESSION_401' });
const sess = await this.sessions.get(`sess:${sid}`); // null if TTL expired / logged out
if (!sess) throw new UnauthorizedException({ bffErrCode: 'ERR_SESSION_401' });
if (!safeEqual(sess.xsrfToken, headerToken)) {
throw new UnauthorizedException({ bffErrCode: 'ERR_SESSION_401' });
}
req['session'] = sess; // downstream reads accountNo/sub from here, NOT from the client
next();
}
}
function safeEqual(a: string, b: string): boolean {
const ba = Buffer.from(a), bb = Buffer.from(b);
if (ba.length !== bb.length) return false;
return timingSafeEqual(ba, bb);
}
// app.module.ts
consumer.apply(SessionXsrfMiddleware).forRoutes({ path: 'api/s/*path', method: RequestMethod.ALL });
The bffErrCode is the same for every 401 branch, but the internal log records the specific branch (missing cookie / no session / wrong token) so operations can trace it without exposing it externally.
4.3 After the middleware: proxying to the API Gateway
When the middleware passes, the BFF attaches accountNo from req.session to an internal header (e.g. X-Account-No) and proxies to the API Gateway. The client cannot set this header itself: the BFF must remove/overwrite any header of the same name coming from the client before proxying. This defense goes hand in hand with the "Source" column in Day 2, Part 1.
5. UI side: attaching the token and handling 401
function readCookie(name: string): string | undefined {
return document.cookie.split('; ').find(c => c.startsWith(name + '='))?.split('=')[1];
}
export async function apiFetch(path: string, init: RequestInit = {}) {
const xsrf = readCookie('xsrf');
const res = await fetch(path, {
...init,
headers: { ...init.headers, 'X-XSRF-TOKEN': xsrf ?? '', 'Content-Type': 'application/json' },
credentials: 'same-origin',
});
if (res.status === 401) return handleUnauthorized(path, init); // Day 2, Part 3
return res;
}
Point to write in the UI spec: read the token on every call, do not cache it at page load, because the token can change after step-up or after logging in again.
6. The "Common session check" spec section for /api/s/*
This is a common process that every /api/s/* endpoint links to:
[Common session check]
① Get the sid cookie. Missing → 401 (ERR_SESSION_401).
② Get the X-XSRF-TOKEN header. Missing → 401 (ERR_SESSION_401).
③ Read Redis sess:{sid}. Does not exist → 401 (ERR_SESSION_401).
④ Constant-time compare sess.xsrfToken with the header. Mismatch → 401 (ERR_SESSION_401).
⑤ Attach accountNo, sub, channel from the session to the request context.
Remove any X-Account-No, X-Sub headers sent by the client.
⑥ Do not extend the TTL (absolute). Continue with endpoint processing.
Notes:
- Every 401 branch returns the same body; the specific branch is only logged internally.
- Does not apply to /api/ns/*, /auth/*.
- UI on receiving 401: see [UI-side 401 handling] (Day 2, Part 3).
For step-up (Day 7, Part 1), this common process is extended with step ⑦ "read stepup:{id} and check context", while ① through ⑥ stay the same. That is why it is split out from the start: add steps, do not rewrite.
7. Common mistakes found in review
| Mistake | Consequence | How to detect |
|---|---|---|
New endpoint placed outside /api/s/* (e.g. /api/v2/transfer) so the middleware does not apply | CSRF + no session check | Grep routes that do not match the prefix |
Comparing the token with === | Theoretical timing attack; low real risk but cheap to fix | Code review |
GET with side effects in /api/s/* | A link click is CSRF even with Lax | Read the endpoint table, Method column |
| Returning 403 for a wrong token and 401 for a missing session | Attacker can tell a right sid from a wrong one | Read the error code table |
| UI caches the token at page load | After logging in again → repeated 401 | Test the re-login flow without reloading |
Proxy does not remove the client's X-Account-No header | Client impersonation | Test by sending a forged header |
Part 3: Logout, 401 handling and the session lifecycle
1. Lifecycle of a logged-in session
Every path leads to the same two end states: the Redis key is gone and the browser has no session cookies. The spec must ensure no path leaves either one behind.
2. Explicit logout
2.1 Three places to clean up
| Where | What to clean up | Who does it |
|---|---|---|
| Redis | DEL sess:{sid}; if there are stepup:*, stepup-mfa:* tied to the session → delete them too | BFF |
| Cookie | sid, xsrf, uid, sid_stepup → Set-Cookie: <name>=; Max-Age=0; Path=/; Secure; HttpOnly... (same attributes as when set) | BFF |
| IdP | The SSO session at Auth0/Keycloak. If not cleared, the next /authorize makes the IdP log the user in again automatically without asking for a password | BFF redirects the browser to the IdP's logout endpoint (RP-initiated logout, Day 4, Part 2) |
2.2 MemberPortal's logout chain
GET /auth/web/logout
① Read sid → sess. If there is no sess, continue anyway (idempotent).
② DEL sess:{sid} and its child sessions.
③ Set-Cookie deleting sid, xsrf, uid, sid_stepup. Do NOT touch APP_SSO_TOKEN.
④ Choose the IdP by sess.idProvider (auth0 | keycloak | null).
No idProvider (App/Operator/mock channel session that did not go through an IdP) → skip ⑤⑥,
302 straight → /auth/web/logout-complete.
⑤ 302 → IdP logout endpoint (Auth0 /v2/logout uses returnTo; Keycloak end_session uses
post_logout_redirect_uri) = https://portal.example.com/auth/web/logout-callback
(the IdP clears its own SSO session)
⑥ IdP 302 → /auth/web/logout-callback
⑦ BFF 302 → /auth/web/logout-complete ("Signed out" screen)
Two design points worth writing down:
- Delete Redis before redirecting to the IdP (step ② before ⑤). If the IdP fails or the user closes the tab midway, the portal session is already dead. The reverse (deleting after the IdP callback) can leave the session alive if the callback never arrives.
- Idempotent: calling logout with no session still returns the normal flow, not 401. A user who clicks logout twice, or calls it after the TTL has expired, must not see an error.
2.3 Deleting cookies correctly
The browser only deletes a cookie when the deleting Set-Cookie has the same name, Domain, and Path as the original cookie. A cookie set with Path=/ cannot be deleted with Path=/auth. The spec states the deletion attributes by referring to the cookie table: "delete with the same attributes as when set".
3. UI-side 401 handling
A 401 reaches the UI for many reasons: TTL expired, logout in another tab, BFF killed the session, missing XSRF because of a bug. The UI does not need to know the detailed cause; the behavior is the same, except for one exception with its own code: bffErrCode = STEPUP_REQUIRED (the session is still valid, it only needs re-authentication for a sensitive operation; Day 7, Part 1).
3.1 Procedure
API /api/s/* returns 401
⓪ Read bffErrCode in the body. If bffErrCode == STEPUP_REQUIRED → this is NOT a lost session:
start the step-up flow (GET /auth/stepup/start?context=..., Day 7, Part 1), do NOT delete cookies,
do NOT push to login. Every other 401 continues to ①.
① Delete cookies: sid, xsrf, uid, sid_stepup (JS deletes non-HttpOnly cookies by setting max-age=0;
HttpOnly cookies such as sid cannot be deleted from JS → call an extra BFF endpoint to delete them,
or have the BFF delete them itself in the 401 response with Set-Cookie)
② Clear sessionStorage (per-session UI data).
③ Do NOT delete APP_SSO_TOKEN. Do NOT clear non-sensitive localStorage settings (theme, language).
④ Does the UA match the app WebView?
yes → POST /auth/app/login
200 → retry the original request (at most once)
403 → "Login failed" screen
no → go to /auth/web/login?successUrl=<current URL>
3.2 Why the BFF should delete HttpOnly cookies itself in the 401 response
JS cannot touch HttpOnly cookies (sid, sid_stepup). If you rely only on the UI, a sid cookie pointing to a dead session will remain: harmless, but it adds log noise and costs the middleware one Redis read per request. The clean design: when the middleware returns 401, it includes a Set-Cookie deleting sid. The spec writes this in the "Common session check" common process: "The 401 response includes headers deleting the sid, xsrf, uid cookies".
3.3 Retry only once
After a successful app SSO, retry the original request exactly once. If it is still 401 → go to the error screen, do not loop. Missing this limit is the classic infinite-loop bug when the backend returns 401 for some other reason (e.g. a wrong endpoint).
4. Session fixation and why SessionID2 must be new
4.1 Attack scenario
1. Attacker creates their own login sequence: GET /auth/web/login → receives temp cookie = L_ATT
2. Attacker tricks the victim into using L_ATT (cookie via another vulnerability, subdomain setting a cookie...)
3. Victim logs in successfully with login:L_ATT
If the BFF REUSES L_ATT as the logged-in session: sess:L_ATT = {the VICTIM's accountNo}
→ attacker already knows L_ATT from step 1 → session hijacked.
If the BFF creates a NEW S2 with a CSPRNG and sets it only on the victim's browser:
→ attacker only knows L_ATT (already DELeted) → gets nothing.
4.2 Rules
- Never use SessionID1 as SessionID2. The logged-in id is always freshly generated after successful authentication.
- The same applies to step-up: after re-authentication,
stepup:{id}gets a new id; do not reusesid_stepup. - On any privilege elevation (login → step-up, operator...), always issue a new id. OWASP principle: "renew session ID after any privilege level change".
This is the second reason (after lifecycle) for splitting the two kinds of session in Day 2, Part 1.
5. Which cookie does the attacker have, and what can they do?
A mandatory analysis for spec writers. Assume the attacker does not have XSS on the portal (if they do, the whole analysis is moot).
| Attacker has | Can do | Why |
|---|---|---|
Only uid | Learns the victim's sub. Cannot call any API | uid is not used for authentication; the BFF only trusts sess.sub. Value: very low (could be used for targeting) |
Only sid | Call /api/ns/* (public anyway). Calling /api/s/* → 401 because the correct X-XSRF-TOKEN is missing. Can call /auth/web/logout to log the victim out (mild DoS) | The middleware needs both sid and a matching xsrf. Logout does not need xsrf (GET redirect) → only a nuisance |
sid + xsrf | Full session takeover until TTL expiry or the victim logs out | Has both factors the middleware requires |
sid_stepup | Almost nothing: the step-up callback also needs a matching state and a code from the IdP | It is just a temporary cookie of one login sequence |
APP_SSO_TOKEN | Call POST /auth/app/login with a fake UA → get a new session for the victim | This token is the app's proof of authentication. The risk is owned by the app team; the BFF mitigates it by making the token one-time or short-TTL on the SSO Token Verify API side (written as a requirement to the app team) |
5.1 Design consequences
- The
sidrow shows thatHttpOnlyonsidis very valuable: XSS can readxsrf(not HttpOnly) but notsid→ it still cannot hijack the session just by reading cookies. (XSS can still call APIs from inside the victim's page; that is a different problem.) - The "can log out" cell of the
sidrow raises a question: should logout require XSRF? MemberPortal chose no, because logout must be a GET redirect to pass through the IdP, and the only risk is being logged out. The spec records this decision under "Design rationale". - The
APP_SSO_TOKENrow shows the boundary of responsibility: the BFF does not control this cookie, so the BFF spec must list its assumptions about it (Secure, HttpOnly, one-time/short TTL) and turn them into requirements for the app team.
6. Error codes and logs
| Situation | Response | Internal log |
|---|---|---|
| Missing sid | 401 ERR_SESSION_401 | reason=no_cookie |
| No session | 401 ERR_SESSION_401 | reason=session_missing sid_hash=<first 8 chars of sha256> |
| Wrong XSRF | 401 ERR_SESSION_401 | reason=xsrf_mismatch |
| Logout with no session | Normal 302 | reason=logout_no_session |
Logging rule: never log the values of sid, xsrf, or tokens; only log a truncated hash to correlate log lines. Logs include bffErrCode so operations can look things up without needing user data.
7. Session lifecycle checklist for spec reviewers
□ Does every failure branch of the callback say "DEL SessionID1"?
□ Does the Login Status API fail / invalid account branch say "do NOT persist SessionID2, no cookies set" (sess was never SET)?
□ Does logout have a branch for sessions without idProvider (App/Operator/mock) → skip IdP logout?
□ Does logout delete Redis BEFORE redirecting to the IdP?
□ Is logout idempotent (no 401 when there is no session)?
□ Is the list of cookies deleted on logout/401 explicit, and does it exclude APP_SSO_TOKEN?
□ Are cookies deleted with the same Domain/Path they were set with?
□ Is SessionID2 a new id, not reusing SessionID1? Same for step-up?
□ Does the UI retry after app SSO at most once?
□ Does the 401 response include Set-Cookie deleting the HttpOnly cookies?
□ Are logs free of sid/xsrf/token values?
Review Questions
-
Why did MemberPortal choose server-side sessions even though stateless JWT scales more easily?
Show answer
Because of two fintech business requirements: (1) account lock/logout must take effect immediately, which is only possible by deleting state on the server; a self-contained JWT lives until
exp, and revoking it means building a denylist, which brings you back to stateful. (2) IdP tokens never leave the server: session data (accountNo, xsrfToken, usedPasskey) lives in Redis and the browser only holds an opaque id; XSS cannot get anything useful besides the id (and the id is HttpOnly). The cost is a dependency on Redis and one Redis read per request, which is acceptable for a BFF; horizontal scaling still works because Redis is shared. -
What problems does splitting SessionID1 and SessionID2 solve? Name at least three.
Show answer
(1) Different lifecycles: state/nonce/code_verifier must die right after the callback to prevent replay, while accountNo/xsrfToken live for 3h; separate keys let you
GETDELall the temporary data at once. (2) Preventing session fixation: SessionID2 is a new id generated after authentication, so an attacker who knows SessionID1 in advance gains nothing. (3) Clear read/write boundaries: the/api/s/*middleware only readssess:*, the callback only readslogin:*; no flow writes across. (4) Safe parallel logins: multiple tabs create multiple independentlogin:*keys that do not overwrite each other. (5) Easy to set different TTLs (SESSION_LOGIN_TTLvsSESSION_TTL). -
Distinguish absolute and sliding TTL. Which one does MemberPortal use for
sess:*and why?Show answer
Absolute: expires exactly N seconds after creation, independent of activity (
SET ... EX Nonce). Sliding: every valid request extends it by N seconds (EXPIREafter each use), so a session can live forever if it stays active. MemberPortal uses absolute forsess:*: it sets a hard limit on the maximum lifetime of a session (including a hijacked one) and simplifies auditing. If you want sliding for a better user experience, you must add an absolute cap (e.g. 12h max) and write both numbers in the spec, because "TTL 3h" means two different behaviors under the two types. -
Where does the
accountNofield in SessionID2 come from? If a new endpoint takes it from the request body, what is the bug?Show answer
From the custom claim
https://claims.example.com/account_noin the signature-verified id_token (web) or from the SSO Token Verify API result (app). Both are trusted server-side sources. If it is taken from client-sent body/query/cookie, the client can claim someone else's accountNo and the BFF will proxy the request to the API Gateway with a forged identity, i.e. a serious authorization bypass (viewing balances, placing orders on another person's account). This is why the data model table must have a "Source" column, and why reviewing a new endpoint means comparing it with sibling endpoints: same field, same source. -
Why use
GETDEL(atomic read and delete) for SessionID1 at the callback instead ofGETand thenDELafter processing?Show answer
To guarantee that each login sequence can be called back only once, even when two callback requests arrive almost simultaneously (user double-click, or an attacker replaying an intercepted callback URL). With
GETthenDELat the end of the function, two parallel requests bothGETsuccessfully and both exchange the code (the IdP will reject the second code, but a round-trip is wasted and inconsistent state may result), or if an error occurs midway andDELis never reached, SessionID1 lives on for 3h, allowing retries.GETDELmakes the temporary data disappear at the moment it is read: the second request sees null → "Login failed". The spec phrases it as: "Read and delete SessionID1 in a single operation". -
Name the three conditions for CSRF to succeed and which one the synchronizer token breaks.
Show answer
(1) The server relies only on the cookie to authenticate the request; (2) the browser automatically sends the cookie with cross-site requests; (3) the attacker knows the request structure. The synchronizer token breaks condition (1): the server additionally requires an
X-XSRF-TOKENheader whose value matchessess.xsrfTokenin Redis. A cross-site page can make the browser send cookies but cannot read thexsrfcookie (different origin), so it cannot attach the correct header → 401. SameSite breaks condition (2) but only partially, so it is a supplementary layer. Condition (3) cannot be broken because the API is a public contract. -
Why does MemberPortal compare the header with the token in Redis instead of with the
xsrfcookie (double-submit)?Show answer
A double-submit cookie only checks header == cookie and needs no state; its weakness is that an attacker can set an
xsrfcookie onexample.comfrom a compromised subdomain (or by cookie tossing) and then send a header with the same value → match. The synchronizer token compares against the authoritative value insess:{sid}on the server, so thexsrfcookie is only a transport channel; overwriting the cookie does not help because Redis still holds the real value. MemberPortal already has server-side sessions, so the extra cost is zero. Conclusion: if you have sessions, use the synchronizer; double-submit is only for stateless systems. -
Why do all failure branches of the middleware return the same 401 with the same body?
Show answer
To avoid revealing internal state to someone probing. If "no session" returned 401 while "wrong token" returned 403, an attacker guessing sids would know when they guessed correctly (the code changes from 401 to 403) even without the token; that turns sid guessing into a process with feedback. The same code and body make every failure look identical. The operational need (knowing which step failed) is met by internal logs that record the specific branch along with
bffErrCode, not by the response. -
A developer adds the endpoint
GET /api/s/orders/cancel?id=123. Point out two problems.Show answer
(1) GET with side effects:
SameSite=Laxstill sends cookies on top-level GET navigation, so a link on a foreign page that the user clicks would cancel the order. Even though the middleware requiringX-XSRF-TOKENwould block it (a link does not attach headers), REST and spec principles are still violated and the SameSite layer becomes pointless. It must become POST/DELETE. (2) Theidparameter in the query leaks into logs/history; for an order cancellation it should go in the body. In addition, the reviewer should compare with the sibling endpoint (POST /api/s/orders) to keep the method and parameter placement consistent. -
Why must the middleware remove a client-sent
X-Account-Noheader before proxying to the API Gateway?
Show answer
Because the API Gateway trusts that header as attached by the BFF from the session. If the BFF only "adds" the header without removing the same-named header from the client, some HTTP clients/proxies will send two values or keep the first one, which is the client's → the API Gateway reads a forged accountNo → access to another account's data. This is the same bug as taking accountNo from the body (Day 2, Part 1), but at the transport layer. The spec states it explicitly: "Remove every internal identity header coming from the client, then attach the value from the session".
- What does MemberPortal's logout delete in the three places, and why does the order "delete Redis first, redirect to IdP afterwards" matter?
Show answer
Redis: DEL sess:{sid} and child sessions (stepup:*, stepup-mfa:*). Cookies: Set-Cookie deleting sid, xsrf, uid, sid_stepup with the same attributes they were set with; APP_SSO_TOKEN is not touched. IdP: redirect the browser to the Auth0/Keycloak logout endpoint (according to sess.idProvider) with post_logout_redirect_uri so the IdP clears its SSO session, preventing the next /authorize from logging in again automatically. The order matters because the redirect to the IdP may not complete (IdP error, user closes the tab, callback never arrives); if you wait for the IdP callback before deleting Redis, the portal session stays alive even though the user believes they have logged out. Deleting Redis first guarantees the portal is in a safe state regardless of what happens afterwards.
- When the UI receives a 401, why is
APP_SSO_TOKENnot deleted, and why is the original request retried only once?
Show answer
APP_SSO_TOKEN is injected into the WebView by the native app as proof that the user is logged in to the app. Deleting it leaves POST /auth/app/login without a token to verify → the WebView cannot SSO again and the user is pushed to the web login screen inside the app: it breaks the SSO experience and forces password entry in the WebView. The BFF does not own this cookie, so it does not delete it. Retry once: after a successful app SSO, call the original request again; if it is still 401 (broken endpoint, XSRF bug, session killed immediately), continuing would create an infinite loop login → 401 → login. Limiting it to once and then going to the error screen lets the user and the operations team see the problem.
- Explain session fixation and how MemberPortal prevents it.
Show answer
The attacker creates a session id in advance that they know (e.g. the login sequence L_ATT), then tricks the victim into using that id when logging in. If the system keeps the id unchanged after authentication, that id is now bound to the victim's identity and the attacker takes over the session without stealing anything. MemberPortal prevents it by always generating a new SessionID2 with a CSPRNG after a successful callback and DELing SessionID1; the id the attacker knew in advance is dead and never becomes a logged-in id. General principle: change the session id after every privilege level change (login, step-up, operator), so stepup:{id} is also a new id and does not reuse sid_stepup.
- The attacker has
sidbut notxsrf. What can and cannot they do? What does this say about the value ofHttpOnlyonsid?
Show answer
They cannot call any /api/s/* because the middleware requires an X-XSRF-TOKEN header matching sess.xsrfToken; missing header → 401. They can call /api/ns/* (public anyway) and GET /auth/web/logout to log the victim out (a nuisance, no data exposure). Lesson: the session needs two factors, sid + xsrf. Because xsrf is not HttpOnly (JS must read it), if sid were not HttpOnly either, an XSS reading cookies would get both and hijack the session from another machine. HttpOnly on sid ensures that an XSS reading cookies gets only half; this is why the two cookies have different attributes, not an inconsistency.
- Why does the BFF spec need to record "assumptions" about
APP_SSO_TOKENeven though the BFF does not create this cookie?
Show answer
Because the attacker analysis table shows that anyone holding a valid APP_SSO_TOKEN can create a new session for the victim via POST /auth/app/login (the UA can be faked). The security of the App channel depends on the attributes of the cookie the app team sets (Secure, HttpOnly, host-only) and on the token lifecycle on the SSO Token Verify API side (one-time or short TTL). The BFF spec does not control these but relies on them, so it must write them as explicit assumptions and turn them into cross-team requirements; otherwise, if the app team changes behavior (e.g. a token that lives 30 days), the portal's security level silently drops without anyone noticing. Writing assumptions = defining the boundary of responsibility.
Hands-on Exercises
Exercise 1: Write secureRandomString and measure entropy
Write the function from section 2, generate 100,000 values, and check for duplicates and output length. Then write a version using Math.random() and explain in words why it must not be used; no need to prove it in code.
Expected output: 0 duplicates; 43-character base64url strings for 32 bytes; the explanation mentions "xorshift128+ is predictable".
Exercise 2: Data model table for mock:{id}
Based on section 5.2, write the data model table for the mock session (POST /auth/mock-session). The Source column for accountNo will be "request body"; explain why that is acceptable here while it is not for sess:*.
Expected output: a table with ≥ 5 fields; the explanation mentions the STAGE guard and the env password, and that mock sessions do not exist in prod.
Exercise 3: Simulate the two sessions with redis-cli
Run Redis locally. Using redis-cli, create login:L1 with a 60s TTL containing minimal JSON; then run GETDEL login:L1 twice in a row and observe. Create sess:S2 with TTL 10800 and use TTL sess:S2 to see the absolute TTL decrease even though you GET it many times.
Expected output: the second GETDEL returns (nil); TTL decreases steadily and does not reset on GET.
Exercise 4: Build a CSRF PoC and then fix it
Create a small Express server with POST /api/s/transfer that only checks the sid cookie. Create an HTML page on another origin that auto-submits a form. Observe the transfer succeed. Then add the middleware from section 4 and run it again.
Expected output: run 1 succeeds (200); run 2 returns 401 because X-XSRF-TOKEN is missing; a same-origin fetch with the header gets 200.
Exercise 5: Bypass double-submit
Change the middleware to compare header == xsrf cookie. From the attack page, use document.cookie = 'xsrf=EVIL; domain=...' (simulate a compromised subdomain with two same-site servers) and then send the header X-XSRF-TOKEN: EVIL. Observe.
Expected output: double-submit is bypassed (200); switching back to the synchronizer (compare against the server store) → 401.
Exercise 6: Write the common process for step-up
Extend the spec block in section 6 with steps ⑦ and ⑧ for endpoints that require step-up: read the sid_stepup cookie? No: read stepup:{id} using an id stored where? Propose your own design and state the error branch explicitly (no child session → which code?).
Expected output: 2 new steps; a proposed dedicated error code (e.g. 401 with a different bffErrCode, or 403) with reasoning; a note "will be cross-checked in Day 7, Part 1".
Exercise 7: Redraw the lifecycle diagram
Without looking at section 1, draw the diagram from login:* to every ending path. For each path, note (a) which Redis key is deleted, (b) which cookies are deleted, (c) who deletes them (BFF/UI/Redis TTL).
Expected output: ≥ 6 paths; no path leaves a live Redis key alongside a live cookie.
Exercise 8: Write handleUnauthorized for the UI
Implement the function from section 3.1 in TypeScript: delete non-HttpOnly cookies, clear sessionStorage, check the UA, call app SSO, retry exactly once, fall back to /auth/web/login?successUrl=. Write tests for: app UA + 200; app UA + 403; regular UA; retry still 401.
Expected output: 4 tests pass; no path calls /auth/app/login more than once for one original request.
Exercise 9: Try session fixation on the PoC
On the PoC from Day 2, Part 2, change the callback to reuse the login sequence id as the logged-in session. Play the attacker: create a login sequence, hand the cookie to the "victim" (an incognito tab), let the victim log in, then use the old cookie from the attacker tab. Then change it to generate a new id and repeat.
Expected output: in run 1 the attacker can access /api/s/* with the old cookie; in run 2 they get 401.
Exercise 10: Fill in the section 7 checklist for a spec you have
Take any login spec you have read (or the spec excerpt in Exercise 3 of Day 1, Part 1) and tick each box. For each empty box, write a one-sentence finding.
Expected output: a 10-box checklist ticked/unticked; ≥ 2 findings pointing at specific locations in the spec.
References
- OWASP Session Management Cheat Sheet — Session ID Properties
- Node.js crypto.randomBytes
- Redis GETDEL
- Redis SET with EX
- OWASP — Session Fixation
- OWASP CSRF Prevention Cheat Sheet
- OWASP — Cross Site Request Forgery
- Chromium — SameSite Updates (Lax + POST)
- Node.js crypto.timingSafeEqual
- NestJS Middleware
- OWASP Session Management Cheat Sheet — Session Expiration & Renewal
- OpenID Connect RP-Initiated Logout 1.0
- Auth0 — Logout
- Keycloak — OIDC Logout endpoints