This lesson combines 3 topics: Overview of the BFF model and the three questions of every login spec, HTTP and the redirect chain in the login flow, Cookie attributes and designing the cookie table for a BFF.
Learning Objectives
- Understand what a Backend-for-Frontend (BFF) is and why fintech systems choose "BFF holds the session" over "SPA holds the token"
- Redraw the overall map of the example system MemberPortal: browser/WebView → BFF → internal API Gateway → Core API
- Know the three questions that every login flow spec must answer clearly
- Distinguish the "entry points" of a multi-channel login system: web, app WebView, step-up, operator, mock
- Know the 2-week (8-day) course roadmap and how to self-check after each lesson
- Review HTTP methods, status codes, headers, query strings and bodies at the level a login spec needs
- Specify the status code for each error branch (400/401/403/404/503) and explain the reasoning
- Distinguish
application/x-www-form-urlencodedfromapplication/json, and understand the per-route body-parser trap - Draw the 302 +
Locationredirect chain of an OIDC login and know which request each cookie travels with - Write the validation rule for
successUrl: well-formed, same origin, appending tracking parameters - Explain each cookie attribute:
Domain,Path,Expires/Max-Age,Secure,HttpOnly,SameSite - Read and defend the MemberPortal cookie table: why
xsrfis not HttpOnly, whysidhas no Expires - Distinguish same-origin from same-site; know that CORS is not related to cookies the way many people think
- Correctly handle cookies injected by a third party (the native app) in a WebView
- Follow the principle:
User-Agentis only used to choose a path, never to grant access
Part 1: Overview of the BFF model and the three questions of every login spec
1. The problem: who holds the user's tokens?
When a web application needs to log in through an Identity Provider (IdP) such as Auth0 or Keycloak, the first architectural question is not "OAuth2 or OIDC", but: once the IdP has authenticated the user, where do the access_token/id_token live?
There are two schools of thought:
| Criterion | (A) SPA holds tokens | (B) BFF holds the session |
|---|---|---|
| Token exposed via XSS | Yes. JS can read it → can send it out | No. The browser only has an opaque session id |
| Token exposed via logs/referer/history | At risk if the token goes through the URL | No, tokens only travel server-to-server |
| Instant revocation | Hard. A JWT lives until exp | Easy. Delete the key in Redis and you are done |
| Needs CSRF protection | No (no cookies used) | Yes. Requires an XSRF token or strict SameSite |
| Backend complexity | Low | Higher: needs a session store, middleware |
| Good fit for | Internal apps, low sensitivity | Fintech, banking, securities |
The IETF document OAuth 2.0 for Browser-Based Apps ranks the BFF as the recommended model for sensitive applications precisely because of the first row of the table: tokens never reach the browser.
Course principle #1: in the BFF model, access_token, id_token and refresh_token exist only on the server. The browser only holds a random session id that means nothing without Redis.
2. Overall map of the example system MemberPortal
The whole course uses one hypothetical system: MemberPortal, the web member portal of the hypothetical securities company "ACME Securities", running at portal.example.com. Users log in with Auth0 (primary IdP) or Keycloak (fallback IdP). Besides the web, the native app ACME Trade App opens a WebView to MemberPortal.
2.1 Components
| Component | Role | Design notes |
|---|---|---|
| Browser / WebView | Runs the UI, holds cookies | Never sees IdP tokens |
| NestJS BFF | The single external entry point; acts as the OIDC client; holds sessions; proxies APIs | It is a confidential client because it can keep IDP_CLIENT_SECRET |
| Redis | Stores sessions (SessionID1, SessionID2, step-up child sessions) | TTL is a security contract, not a technical detail |
| Internal API Gateway | Receives requests that already have a valid session, calls the Core API | Not exposed to the internet |
| Auth0 / Keycloak | Authenticates users, issues id_tokens | The BFF trusts the IdP by verifying the id_token |
| SSO Token Verify API | Verifies the native app's opaque token | Server-to-server, with its own API key |
2.2 Two API groups behind the BFF
/api/s/*(secured): requires a validsidand anX-XSRF-TOKENheader matching the session. Missing either → 401./api/ns/*(non-secured): no session required, e.g. fetching maintenance info or public catalogs.
Separating the two prefixes right in the URL lets the middleware decide quickly and tells spec readers at a glance which endpoints require a session.
3. The three questions every login spec must answer
A login spec can be 50 pages long, but the reviewer only needs to check whether it clearly answers these three questions. If any one is left blank, the spec is incomplete.
3.1 Q1 applied to MemberPortal
| Entry point | Who authenticates | How the BFF trusts it |
|---|---|---|
/auth/web/* | Auth0 (or Keycloak on failover) | Verify the id_token: signature (JWKS), iss, aud, exp, nonce, connection claim, auth_time |
/auth/app/login | The native app, which logged in earlier and injects APP_SSO_TOKEN | Call the SSO Token Verify API server-to-server; it cannot self-verify because the token is opaque |
/auth/stepup/* | Auth0 with a dedicated client (passkey or password) | Verify the id_token as for web, plus an auth_time check because of prompt=login |
/auth/operator/* | The company's internal IdP (JWT operator_token in the Authorization header) + Operator Account Status API | Verify the token signature via the internal JWKS, take operatorId from a claim (not from the body), then check permission on the accountNo via the API |
/auth/mock-session | Nobody. This is a test backdoor | Guard: STAGE ∈ allowed set + MOCK_LOGIN_PASSWORD |
Lesson: the same session model but several different sources of trust. The spec must state the source of trust for each entry point.
3.2 Q2 applied to MemberPortal
| Redis key | Name | TTL | Deleted when |
|---|---|---|---|
login:{id} | SessionID1 (login sequence) | SESSION_LOGIN_TTL | The callback finishes (whether it succeeds or fails) |
sess:{id} | SessionID2 (logged in) | SESSION_TTL | Logout, TTL expiry, the BFF detects an invalid account |
stepup:{id} | Step-up child session | Fixed 600s | TTL expiry or when the business operation completes (depending on context) |
stepup-mfa:{id} | MFA management child session | = the access_token's expires_in | TTL expiry |
mock:{id} | Fake session for testing | MOCK_SESSION_TTL | TTL expiry |
Each row is covered in detail in Day 2, Part 1 and Day 7, Part 1. Today you only need to see that a real login system has more than one kind of session, and each kind has its own lifecycle.
3.3 Q3 applied to MemberPortal
The point most often missed when writing a spec: the "What is deleted?" column. Authors usually only write the target screen and forget to say which session is deleted and whether cookies are set. That is exactly what creates "orphaned session" or "cookie pointing to a deleted session" vulnerabilities.
4. Why does fintech choose this model?
4.1 Business requirements drive technical requirements
| Business requirement | Technical consequence |
|---|---|
| Locking an account must take effect immediately | Sessions must be revocable → server-side sessions, not self-contained JWTs |
| Withdrawals require re-authentication | Needs step-up authentication with short-TTL child sessions |
| Multiple channels (web, app, staff) | Same session model, different issuance |
| Only some account types may use the portal | Check the account type at several layers (IdP, app, BFF) |
| IdP maintenance must not take login down | Fallback IdP + health check |
| Access auditing | Record login history, logs with traceable error codes |
4.2 Trade-offs you must accept
- Stateful: the BFF depends on Redis. Redis down → all logins down. Redis needs HA.
- More complex than a pure SPA: extra XSRF middleware, a cookie table, a session model.
- Tied to the domain: the
sidcookie is bound toportal.example.com; extending to another domain requires a redesign.
A good spec records these trade-offs in its "Design rationale" section so that nobody later switches to JWT on their own because it is "simpler".
5. Reading a login spec as a reviewer
When you receive a new login flow spec (a new channel, a new IdP, a new step-up), read it in the following order, not top to bottom:
Step 1. Find the sequence diagram. Count the redirects. Mark where sessions are created.
Step 2. Find the "data stored in the session" table. Check that every field has a source (from where?) and a TTL.
Step 3. Find the cookie table. Check Secure/HttpOnly/SameSite for each cookie.
Step 4. Find the list of error branches. Cross-check against the "What is deleted?" column in section 3.3.
Step 5. Find the environment conditions of test endpoints. If there are none → finding.
Step 6. Only then read the detailed processing description.
Why: the sequence and the session table are the "skeleton"; the detailed description is just the "flesh". If the skeleton is wrong, nice flesh is meaningless.
5.1 A typical real-world finding
The spec says: "When the API returns 401, the screen clears all cookies and returns to the login screen." Finding: on the App channel, the
APP_SSO_TOKENcookie is injected by the native app. If it is cleared too, the WebView cannot SSO again and the user is forced to type a password inside the app. The spec must state the list of cookies to clear, not "all".
6. The 2-week (8-day) course roadmap
| Stage | Topics | Output after the stage |
|---|---|---|
| Week 1, Days 1–2 | Foundations: HTTP, redirects, cookies, sessions, CSRF, logout | Draw the MemberPortal cookie table + session table yourself and explain every attribute |
| Week 1, Days 3–4 | OAuth 2.0 / OIDC by the book: Authorization Code, PKCE, state, nonce, id_token, client_credentials, RP-initiated logout | Draw the Web login sequence diagram in Mermaid from memory, with an RFC cross-reference table |
| Week 2, Days 6–7 | Advanced pieces: multi-channel, app SSO, multi-layer authz, IdP failover, step-up/MFA, test backdoors; spec-writing skills + review checklist | Write a spec for a hypothetical channel in the correct format and self-review it with the 10-item checklist |
Study rule: do not skip stages. Days 3–4 assume you are solid on cookies/sessions; Week 2 assumes you are solid on OIDC.
Part 2: HTTP and the redirect chain in the login flow
1. HTTP at the level a login spec needs
A login spec does not require you to memorize RFC 9110, but it does require you to use four things correctly and consistently: method, status, header, body.
1.1 Method
| Method | Used for | MemberPortal example |
|---|---|---|
| GET | Navigation, redirects, callbacks from the IdP | GET /auth/web/login, GET /auth/web/login-callback?code=...&state=... |
| POST | Changing state, sending sensitive data | POST /auth/app/login, POST /auth/mock-session, POST /oauth/token (BFF calls the IdP) |
| DELETE | Rarely used in login; logout is usually a GET redirect so it can go through the IdP | — |
Rule: this design uses response_mode=query (the Authorization Code default), so the callback from the IdP is a GET and all callback data is in the query string. (OIDC also has response_mode=form_post, where the callback is a POST with a form-urlencoded body — MemberPortal does not use it.) That is why code must be short-lived and one-time: it travels through the URL and can leak into logs/referer.
1.2 Status codes and MemberPortal conventions
| Status | Standard HTTP meaning | MemberPortal convention |
|---|---|---|
| 200 | OK | API succeeded; POST /auth/app/login succeeded (UI retries the original request) |
| 302 | Found (redirect) | The whole OIDC chain; back to successUrl / error screen |
| 400 | Bad Request | Wrong body type; operator mode calling the web endpoint by mistake (isOpe=true calling /auth/web/login) |
| 401 | Unauthorized | Session invalid, expired, or X-XSRF-TOKEN missing/wrong on /api/s/* |
| 403 | Forbidden | POST /auth/app/login rejected (invalid token or ineligible account) |
| 404 | Not Found | Test endpoint disabled by STAGE (so the endpoint's existence is not revealed) |
| 503 | Service Unavailable | System under maintenance |
Two things worth noting:
- 401 vs 403: 401 means "I don't know who you are, please authenticate again"; 403 means "I know who you are but you are not allowed". So
/api/s/*without a session returns 401 (the UI switches to login), while a rejected/auth/app/loginreturns 403 (the UI shows "Login failed" and does not retry). - Deliberate 404: when the
/auth/mock-sessionguard is not satisfied (STAGE is prod, or the password is wrong), return 404 instead of 401/403. Returning 403 admits "this endpoint exists and you lack permission", a hint for scanners. Returning 404 looks exactly like a non-existent path.
1.3 Important headers in the login flow
| Header | Direction | Role |
|---|---|---|
Location | Response | Redirect target of a 302 |
Set-Cookie | Response | Issues/deletes cookies; one header per cookie |
Cookie | Request | Attached automatically by the browser by domain/path |
X-XSRF-TOKEN | Request | Attached manually by JS for /api/s/* |
User-Agent | Request | Identifies the app's WebView to choose a path, not to grant access |
Content-Type | Both | Determines which body parser can read the body |
Authorization: Bearer | Request (BFF → IdP/API) | Used by the BFF when calling the Management API; never sent from the browser to the BFF |
2. Body: form-urlencoded vs JSON and the body-parser trap
2.1 Two formats, two places of use
POST /oauth/token HTTP/1.1 POST /auth/mock-session HTTP/1.1
Host: <idp-domain> Host: portal.example.com
Content-Type: application/x-www-form- Content-Type: application/json
urlencoded
{
grant_type=authorization_code "accountNo": "1234567",
&code=abc123 "password": "<MOCK_LOGIN_PASSWORD>"
&redirect_uri=https%3A%2F%2Fportal... }
&client_id=portal-web
&client_secret=<client_secret>
&code_verifier=dBjftJeZ4CVP...
- The IdP token endpoint (RFC 6749 §4.1.3) requires
application/x-www-form-urlencoded. Sending JSON to Auth0's/oauth/tokenis mostly still accepted, but Keycloak does not accept it. The spec should state form-urlencoded explicitly so it does not depend on one IdP's lenient behavior. - The BFF's internal endpoints accept JSON, because JSON via
fetchis the most natural way for the UI to call them.
2.2 The trap: per-route body parser
In NestJS, bodyParser is enabled globally by default. Many BFFs disable the global body parser so the /api/* reverse proxy can forward the raw body (raw stream) to the API Gateway without parsing and re-serializing it. In that case, any endpoint that needs to read the body must attach its own parser:
// main.ts
const app = await NestFactory.create(AppModule, { bodyParser: false });
// auth.module.ts
export class AuthModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(json()) // attach only the JSON parser
.forRoutes({ path: 'auth/mock-session', method: RequestMethod.POST });
}
}
The consequence to record in the spec:
POST /auth/mock-sessiononly acceptsContent-Type: application/json. Sendingapplication/x-www-form-urlencoded→ the body is not parsed → required fields are missing → 400.
A tester using Postman who picks the "form-data" tab by mistake will get a 400 and think the server is broken. Stating the Content-Type right in the parameter table saves half a day of debugging.
2.3 Self-check question
Why not just re-enable the global bodyParser for convenience? Hint: the /api/s/* reverse proxy must forward the raw body (including multipart uploads) to the API Gateway. Parsing and re-serializing breaks multipart, costs CPU and may change the order of JSON fields.
3. Redirect chain: the backbone of OIDC
3.1 The 302 + Location mechanism
The browser receives a 302 with a Location header and automatically issues a new GET request to Location. Cookies are attached to the new request based on the domain of Location, not the domain of the previous request.
Request 1 GET https://portal.example.com/auth/web/login
Response 1 302 Location: https://<idp>/authorize?client_id=portal-web&state=S1&nonce=N1&code_challenge=...
Set-Cookie: login_sid=L1; Secure; HttpOnly; SameSite=Lax ← SessionID1
Request 2 GET https://<idp>/authorize?... (portal cookies do NOT go along, different domain)
Response 2 200 (IdP login screen) ... user enters password ...
Response 2' 302 Location: https://portal.example.com/auth/web/login-callback?code=C1&state=S1
Request 3 GET https://portal.example.com/auth/web/login-callback?code=C1&state=S1
Cookie: login_sid=L1 ← back on the portal, the cookie goes along
Response 3 302 Location: https://portal.example.com/home (successUrl)
Set-Cookie: sid=S2; Secure; HttpOnly; SameSite=Lax ← SessionID2
Set-Cookie: xsrf=X2; Secure; SameSite=Lax
Set-Cookie: uid=U1; Secure; SameSite=Lax
Set-Cookie: login_sid=; Max-Age=0 ← delete SessionID1
Request 4 GET https://portal.example.com/home
Cookie: sid=S2; xsrf=X2; uid=U1
3.2 What breaks this chain?
| Break point | Symptom | Common cause |
|---|---|---|
Request 3 has no login_sid | The callback cannot find SessionID1 → "Login failed" | The SessionID1 cookie is SameSite=Strict (the redirect from the IdP is cross-site → not sent). Must use Lax |
Request 3 has a state other than S1 | State comparison fails | The user opened 2 login tabs in parallel; the second tab overwrote SessionID1 |
| Response 3 sets cookies but Request 4 does not carry them | Going to /home gets 401 again | Wrong cookie Domain, or Path does not cover /home |
| Location points to an unknown domain | Open redirect | successUrl is not validated |
The first break point is why the login-related cookies in MemberPortal use SameSite=Lax rather than Strict: with Lax, cookies are still sent on the top-level GET navigation back from the IdP. Details in Day 1, Part 3.
3.3 How to describe redirects in a spec
Don't write "redirect the user to the IdP". Write a table, one row per hop:
| # | From | To | Method/Status | Cookies set | Cookies read |
|---|---|---|---|---|---|
| 1 | Browser | BFF /auth/web/login | GET | — | — |
| 2 | BFF | IdP /authorize | 302 | SessionID1 | — |
| 3 | IdP | BFF /auth/web/login-callback | 302 → GET | — | SessionID1 |
| 4 | BFF | successUrl | 302 | SessionID2, xsrf, uid; delete SessionID1 | — |
This table matches the sequence diagram (Day 4, Part 3) and the list of error branches 1-to-1.
4. Validating successUrl: preventing open redirect
GET /auth/web/login?successUrl=... receives the destination to return to after login. This is client-controlled input, and the classic source of open redirects.
4.1 Three layers of checks
const DEFAULT_FALLBACK = 'https://www.example.com/';
export function normalizeSuccessUrl(raw: string | undefined, bffDomain: string): string {
if (!raw) return `https://${bffDomain}/`;
let url: URL;
try {
url = new URL(raw); // [1] well-formed
} catch {
return `https://${bffDomain}/`;
}
if (url.origin !== `https://${bffDomain}`) { // [2] same origin, scheme included
return DEFAULT_FALLBACK;
}
return url.toString();
}
Common mistakes when writing the rule:
- Comparing with
startsWith('https://portal.example.com')→https://portal.example.com.evil.net/slips through. You must compare the origin after parsing. - Comparing only
hostnameand forgetting the scheme →http://portal.example.com/slips through, opening the door to downgrade. - Allowing the relative path
/homebut not blocking//evil.net/home(a protocol-relative URL).new URL('//evil.net/home', base)gives the originevil.net. If you accept relative paths, parse with a base and still compare the origin.
4.2 Why fall back to the company home page instead of showing an error?
MemberPortal's design decision: a successUrl on the wrong domain is not the user's fault but a sign that the link was tampered with. Sending the user to https://www.example.com/ is safer than showing an error page containing a foreign URL (which could be used for phishing). The spec must state that this is intentional behavior, with the reasoning, so nobody later "fixes the bug" by turning it into an error.
5. Appending tracking parameters to successUrl
A common business requirement: keep tracking parameters (e.g. Google Analytics linker _gl) through the login flow so the analytics session is not lost. The BFF receives _gl at /auth/web/login, stores it in SessionID1, and appends it when redirecting to successUrl.
5.1 Appending rule
Don't concatenate strings yourself. Use URLSearchParams:
export function appendTracking(successUrl: string, gl?: string): string {
if (!gl) return successUrl;
const url = new URL(successUrl);
url.searchParams.set('_gl', gl); // handles ?/&, encoding, keeps the fragment
return url.toString();
}
5.2 What the spec must say
_glis only appended once successUrl has passed the checks in section 4 (appending to a foreign URL = helping the attacker carry tracking away).- The
_glvalue is URL-encoded; its content is not validated because it is an opaque third-party string, but limit its length (e.g. 512 characters) to prevent stuffing data into the session. - If successUrl already contains
_gl, overwrite or keep? MemberPortal chooses to overwrite with the latest value. Write it in the spec, because both choices are reasonable.
6. From HTTP to the parameter table in the spec
Every endpoint in the MemberPortal spec has a fixed parameter table, organized by location. Example GET /auth/web/login:
| Item | Location | Required | Value / Rule |
|---|---|---|---|
successUrl | query | No | Absolute URL; must be well-formed and same origin https://{BFF_DOMAIN}; otherwise → fallback https://www.example.com/ |
failureUrl | query | No | Same as above |
_gl | query | No | Tracking string, ≤ 512 characters, appended to successUrl on redirect |
isOpe | query | No | true → returns 400 (operators use /auth/operator/login) |
User-Agent | header | Yes (sent automatically by the browser) | Only used for logging/choosing a path |
And POST /auth/mock-session:
| Item | Location | Required | Value / Rule |
|---|---|---|---|
Content-Type | header | Yes | Must be application/json; otherwise → 400 |
accountNo | body | Yes | 7-digit numeric string |
password | body | Yes | Compared with MOCK_LOGIN_PASSWORD; wrong → 404 |
channel | body | No | Web | App; default Web (stored in the session to test channel-specific flows) |
| — | env | — | STAGE ∉ {dev, stub, stg} → 404 before reading the body |
Note the order: check STAGE before reading the body, so the prod environment never parses this endpoint's body.
Part 3: Cookie attributes and designing the cookie table for a BFF
1. What a cookie means to a spec writer
A cookie is the only mechanism that lets the browser automatically attach a session identifier to requests without any JS involvement. That very "automatic" nature is both a strength (the OIDC redirect chain works) and a weakness (CSRF). The six attributes below decide when, where to, and by whom a cookie is sent and read.
2. Each attribute and the design decision
2.1 Domain
| Setting | Sent to | Notes |
|---|---|---|
| Not set (host-only) | Only the exact host that set it (portal.example.com) | Safest default |
Domain=example.com | Every subdomain of example.com | The session cookie leaks to blog.example.com, staging.example.com |
MemberPortal does not set Domain for session cookies: only portal.example.com receives sid. If SSO across several subdomains is needed later, redesign it deliberately; do not widen Domain "for convenience".
2.2 Path
Path=/ for session cookies because the APIs are under /api/s/* and pages are at /home, /account/*. Setting Path=/api would make requests to /auth/web/logout go without the cookie. Path is not a security mechanism: JS at /a can still read a Path=/b cookie on the same origin by creating an iframe.
2.3 Expires / Max-Age: session cookie vs persistent cookie
| Type | How to set | Lives until |
|---|---|---|
| Session cookie | Do not set Expires/Max-Age | The browser closes (in practice many browsers restore sessions, so it is not reliable) |
| Persistent cookie | Max-Age=10800 or Expires=<date> | It expires, even across browser restarts |
MemberPortal chooses a session cookie for sid. Reason: the real TTL lives in Redis (SESSION_TTL). The cookie is only the "key", Redis is the "lock". If you set Expires on the cookie equal to the Redis TTL, the two clocks drift (Redis counts from creation, the cookie follows the client machine's clock), creating windows where the cookie exists but the session is gone or vice versa. With no Expires on the cookie, every "still valid or not" decision comes down to a single source: Redis.
Trade-off: a browser that restores sessions may keep the sid cookie longer than expected, but that is harmless because Redis has already deleted the key → 401 → the UI clears the cookie.
2.4 Secure
The cookie is only sent over HTTPS. Every MemberPortal cookie is Secure, including the non-sensitive uid, because there is no reason for any cookie to travel over HTTP. On localhost browsers still accept Secure cookies over HTTP, so developers do not need to turn it off.
2.5 HttpOnly
JS cannot read the cookie via document.cookie. This is the line of defense against XSS stealing cookies. The design question is not "turn it on or not" but "which cookies must JS read?" Only those cookies are not HttpOnly.
2.6 SameSite
| Value | Which cross-site requests carry the cookie |
|---|---|
Strict | Never |
Lax | Only top-level navigation via GET (clicking a link, a 302 redirect). Not on POST, iframe, fetch, img |
None | Every request (requires Secure) |
MemberPortal uses Lax for all session cookies because the redirect back from the IdP is a cross-site top-level GET. Strict breaks OIDC. Lax still blocks cross-site POST (basic CSRF) but is not enough: GETs with side effects via top-level navigation, a compromised same-site subdomain, and old browsers that do not understand SameSite still get through. (Chromium's "Lax + POST within the first 2 minutes" exception only applies to cookies that do not declare SameSite and are defaulted to Lax by the browser; MemberPortal declares SameSite=Lax explicitly so it is not affected.) That is why a synchronizer token is also needed (Day 2, Part 2).
3. The MemberPortal cookie table and the reason for each row
| Cookie | Content | Secure | HttpOnly | SameSite | Expires | Created by |
|---|---|---|---|---|---|---|
login_sid | Temporary SessionID1 for the login sequence | ✔ | ✔ | Lax | none | BFF |
sid | SessionID2 (logged in) | ✔ | ✔ | Lax | none (session cookie) | BFF |
xsrf | XSRF token | ✔ | ✘ | Lax | none | BFF |
uid | user id (sub) | ✔ | ✘ | Lax | none | BFF |
sid_stepup | Temporary SessionID for the step-up login sequence | ✔ | ✔ | Lax | none | BFF |
APP_SSO_TOKEN | 64-hex opaque token | set by app | set by app | set by app | set by app | Injected by the native app |
3.1 Why is xsrf NOT HttpOnly?
MemberPortal's CSRF protection is a synchronizer token: the token lives in the Redis session, and the UI must send that token back in the X-XSRF-TOKEN header on every /api/s/*. To send it, JS must be able to read the token → the xsrf cookie cannot be HttpOnly.
sequenceDiagram
participant B as Browser
participant BFF
Note over B: read document.cookie → xsrf=X2
B->>BFF: fetch('/api/s/balance', { headers: {'X-XSRF-TOKEN': 'X2'} })
Note over BFF: Cookie: sid=S2 (auto-attached)<br/>Header: X-XSRF-TOKEN: X2 (attached by JS)<br/>Redis sess:S2.xsrfToken === X2 ? ✔A foreign page (attacker.net) can make the browser send the sid and xsrf cookies to the portal (if SameSite allows it), but it cannot read the xsrf value because it is a different origin → it cannot attach the correct header → 401. That is why exposing xsrf to same-origin JS is acceptable: same-origin XSS is already a far bigger disaster than CSRF.
3.2 Why is uid not HttpOnly, and is it a secret?
uid holds the user's sub so the UI can display and distinguish the logged-in account, and use it as a client-side sessionStorage key. It has no authentication value: sending someone else's uid does not help an attacker because the BFF only trusts sess:{sid}.sub in Redis. The spec must state this explicitly so that nobody writes code that takes accountNo or sub from the uid cookie instead of from the session.
3.3 Why are sid and sid_stepup separate?
Step-up authentication (Day 7, Part 1) has its own login sequence with the IdP. If both shared the sid cookie, the step-up callback would overwrite the logged-in session and log the user out. sid_stepup only lives during re-authentication, and is HttpOnly because JS does not need to read it.
4. Cookies injected by a third party: APP_SSO_TOKEN
After the user logs in inside the app, the native ACME Trade App injects the APP_SSO_TOKEN cookie into the WebView before opening portal.example.com. The BFF does not create this cookie, it only reads it.
4.1 Three consequences for the spec
- The BFF neither sets nor deletes
APP_SSO_TOKEN. When the API returns 401, the UI clearssid,xsrf,uidand sessionStorage, but does not clearAPP_SSO_TOKEN. Clearing it breaks SSO: the WebView cannot log in again automatically and the user is pushed to the web password screen inside the app. - The BFF does not trust the token's content. The token is opaque; the BFF does not know what is inside. Only the SSO Token Verify API (server-to-server, with its own API key) can confirm it.
- The cookie attributes are decided by the app. The BFF spec writes "set by the app" and records the minimum requirements sent to the app team: Secure, HttpOnly, host-only
portal.example.com.
4.2 List of cookies cleared on 401 (must be stated explicitly)
| Cookie | Cleared on 401? | Reason |
|---|---|---|
sid | ✔ | The session is gone; keeping the cookie only causes repeated 401s |
xsrf | ✔ | Bound to the lost session |
uid | ✔ | Avoid displaying the wrong user |
sid_stepup | ✔ | If still present |
APP_SSO_TOKEN | ✘ | Managed by the app; needed to SSO again |
| sessionStorage | ✔ | Per-session UI data |
A spec that says "clear all cookies" is wrong. A correct spec contains this table.
5. Same-origin, same-site, CORS: three concepts that often get mixed up
| Concept | What it compares | Effect on cookies |
|---|---|---|
| Same-origin | Identical scheme + host + port | JS can only read document.cookie of its own origin |
| Same-site | Same eTLD+1 (example.com), same scheme (schemeful) | Decides whether SameSite sends the cookie |
| CORS | Which origins the server allows to read the response | Does not decide whether cookies are sent; only decides whether JS can read the response (credentials: 'include' + Access-Control-Allow-Credentials) |
Practical consequences for MemberPortal:
- The UI and the BFF share the origin
https://portal.example.com→ no CORS needed, fetch carries cookies automatically. The spec should state this assumption explicitly; if the UI moves toapp.example.comtomorrow, CORS with credentials must be enabled and SameSite reviewed (still same-site because both are underexample.com, but a different origin). successUrlmust be the same originhttps://{BFF_DOMAIN}, not just the same site. Same site but a different subdomain is still considered wrong and falls back to the company home page.- The IdP is on a completely different domain → the redirect back is cross-site → Lax is needed.
6. User-Agent: choose a path, never grant access
The UI uses the User-Agent string to detect that it is running inside the app's WebView (e.g. ACMETradeApp/2.1 (iOS)), so that on a 401 it calls POST /auth/app/login instead of sending the user to web login. The BFF checks the UA again at /auth/app/login.
A principle that must be written into the spec:
The UA can be spoofed freely. The UA only decides which flow is attempted, not what the user is granted. Granting a session depends entirely on the result of the SSO Token Verify API and the account type check.
If an attacker spoofs the app's UA in a regular browser but has no valid APP_SSO_TOKEN → 403, nothing gained. If an attacker uses a regular UA but has a valid token → goes to web login, nothing extra gained either. The UA check in the BFF is only for early rejection and logging, not a security layer.
7. Writing the cookie section of the spec
Minimum template for each cookie:
Name: sid
Purpose: Identifies SessionID2 (the logged-in session)
Value: 32-byte CSPRNG string, base64url (see Common Processes)
Domain: host-only (portal.example.com)
Path: /
Expires: not set (session cookie); real TTL in Redis SESSION_TTL
Secure: yes
HttpOnly: yes
SameSite: Lax — reason: the IdP callback is a cross-site top-level GET
Set when: /auth/web/login-callback succeeds; /auth/app/login 200; /auth/mock-session 200
Deleted when: /auth/web/logout; the UI receives 401 from /api/s/*
Read by: BFF only (session middleware)
The "Set when" and "Deleted when" lines are what reviewers scrutinize the most, because they must match every branch in the detailed processing section.
Review Questions
-
Why does the "BFF holds the session" model protect tokens from XSS better than "SPA holds the token", yet require extra CSRF protection?
Show answer
In the BFF model, the browser only has the
sidcookie, a random opaque string; the access_token/id_token live in Redis on the server. XSS running in the browser cannot get the IdP tokens even if it can read non-HttpOnly cookies. In exchange, because authentication is cookie-based, the browser automatically sends cookies with every request toportal.example.com, including requests initiated by a foreign page. That is the precondition for CSRF, so the BFF must have CSRF protection (a synchronizer token via theX-XSRF-TOKENheader, covered in Day 2, Part 2). An SPA holding tokens uses anAuthorizationheader attached manually by JS, which a foreign page cannot attach, so it does not need CSRF protection but exposes the token to XSS. -
List the three questions every login spec must answer. For MemberPortal's
/auth/app/loginentry point, how is question 1 answered?Show answer
The three questions: (1) Who authenticates the user and how does the BFF trust that result; (2) Where does the login state live, for how long, and when is it deleted; (3) What happens on failure. For
/auth/app/login: the user was authenticated earlier by the native app; the app injects theAPP_SSO_TOKENcookie (opaque, 64 hex) into the WebView. The BFF cannot self-verify this token because it is not a JWT, so it must call the SSO Token Verify API server-to-server (with its own API key) to getsub,accountNo,accountType,passkeyFlag. Only when the API returns valid and the account type is online-trading does the BFF issue SessionID2. -
Why must the spec have a "Which session is deleted?" column for each error branch, instead of only writing the target screen?
Show answer
Because vulnerabilities usually live in leftover state, not in screens. If the callback fails because of a wrong state and SessionID1 is not deleted, an attacker can retry many times with the same login sequence. If the Login Status API fails after SessionID2 has been created, and it is neither deleted nor stated "do not set cookies", a valid logged-in session may exist in Redis for an account that is not allowed to log in. The "What is deleted?" column forces the spec writer to think about the lifecycle of each session in each branch, and makes it checkable for the reviewer.
-
Why does MemberPortal separate
/api/s/*and/api/ns/*right at the URL prefix?Show answer
So the middleware decides quickly and explicitly: every
/api/s/*request must have a validsidand a matchingX-XSRF-TOKEN, otherwise → 401;/api/ns/*skips the session check. The second benefit is for spec readers: the endpoint alone tells you the security requirement without digging through each description. The third benefit is reducing the risk of "forgetting to attach the guard" to a new endpoint, because the rule applies by prefix rather than per route. Trade-off: if an API has both a public part and a private part, it must be split into two endpoints. -
Name three trade-offs of the stateful BFF model that the spec should record in its "Design rationale" section.
Show answer
(1) Dependency on Redis: if Redis is unavailable, no login and no request authentication is possible; it needs HA/replicas and a degradation plan. (2) Complexity: XSRF middleware, a cookie table with many attributes, several session types with different TTLs; newcomers easily misunderstand it. (3) Tied to the domain: the
sidcookie is bound toportal.example.com; extending to another domain or pure mobile requires a redesign (e.g. SSO via an opaque token like the App channel). Record these so nobody later switches to client-side JWT on their own because it is "simpler" and loses instant revocation. -
Why does
/api/s/*without a session return 401, while a rejectedPOST /auth/app/loginreturns 403? If the two codes were swapped, where would the UI go wrong?Show answer
401 means "not authenticated, please authenticate again", so the UI catches 401 to switch to the login flow (web or app SSO). 403 means "I know you but you are not allowed", so the UI shows "Login failed" and stops. If
/auth/app/loginreturned 401 on rejection, the UI would try app SSO again → 401 again → an infinite loop. If/api/s/*returned 403 without a session, the UI would show an error instead of sending the user to login, and the user would have no way out. The meaning of the status codes is a contract between the BFF and the UI and must be in the spec. -
The guard of
POST /auth/mock-sessionis not satisfied (STAGE=prod). Why return 404 instead of 403?Show answer
403 confirms that the endpoint exists and is being blocked, i.e. it reveals that there is a "test backdoor" on production, inviting scanners to find a way past the guard (guessing the env password, looking for a stage misconfiguration). 404 makes the endpoint look like any other non-existent path and gives no information. Principle: endpoints meant only for test environments must be invisible in environments where they are not allowed, and the spec must state that the behavior on guard failure is 404, along with the guard conditions (valid STAGE + matching password).
-
If the SessionID1 cookie is set to
SameSite=Strict, where does the redirect chain break and why?Show answer
It breaks at the step where the IdP redirects back to
/auth/web/login-callback. This request is issued by the browser after a 302 from the IdP domain, so it is a cross-site navigation. WithStrict, the browser does not sendportal.example.comcookies on requests initiated from another site, even top-level GETs. The callback has no SessionID1 → it cannot find state/nonce/code_verifier → "Login failed". WithLax, top-level GET navigation still carries the cookie so the callback works, while cross-site POST is still blocked. That is why MemberPortal uses Lax for all session cookies and compensates for CSRF with a synchronizer token. -
What vulnerability does the check
successUrl.startsWith('https://portal.example.com')have? How do you fix it?Show answer
https://portal.example.com.evil.net/xstarts with that string so it slips through, leading to an open redirect: after logging in, the user is sent to the attacker's page (possibly a phishing page that looks like the portal). Fix: parse withnew URL(); if it throws → not well-formed; compareurl.origin === 'https://' + BFF_DOMAIN(the origin includes scheme + host + port, so it also blockshttp://and unknown subdomains). Do not accept protocol-relative//evil.net. Wrong domain → replace with the company home pagehttps://www.example.com/, never use the received URL. -
Why should
STAGEbe checked before parsing the body of/auth/mock-session, and why does this endpoint need its own JSON parser?
Show answer
Check STAGE first so that on production the request gets a 404 immediately, without spending CPU parsing the body and without creating any data-processing path for an endpoint that should not exist there; it also avoids parse errors leaking information (stack traces, missing-field messages) before the guard runs. It needs its own parser because the BFF disables the global bodyParser so the /api/* reverse proxy can forward the raw body (multipart, large JSON) to the API Gateway; if json() is not attached to this route, req.body is undefined → every request is missing fields → 400. The spec must state that the accepted Content-Type is application/json.
- If
xsrfwere made HttpOnly to be "safer", what would happen to the CSRF protection?
Show answer
The mechanism collapses completely. A synchronizer token requires JS to read the token value and attach it to the X-XSRF-TOKEN header; HttpOnly prevents document.cookie from reading it → JS has no token → every /api/s/* request gets a 401 from the middleware for the missing header. The only way to stay HttpOnly is to switch to a different model (the server embeds the token in the HTML/response body, or double-submit cookie with a separate cookie), which is a design change, not flipping a flag. Making xsrf readable by same-origin JS does not create a CSRF vulnerability because pages on other origins cannot read this cookie.
- Why does
sidnot set Expires even though the Redis session has a 3-hour TTL? What goes wrong if Expires = 3 hours?
Show answer
To have a single source of truth for session lifetime: Redis. The cookie is just a key; Redis decides whether the lock still exists. If Expires is set on the cookie: (1) the two clocks (the server that created the session, the client holding the cookie) drift → there are windows where the cookie has expired but the session is still alive (the user is logged out early) or the cookie is alive but the session has expired (harmless, it will 401). (2) When the Redis TTL changes per environment (SESSION_TTL), you must remember to change the cookie too. (3) If sliding TTL is used in Redis later, a fixed cookie Expires will be wrong. A session cookie eliminates this whole class of bugs.
- A spec says "when the API returns 401, the UI clears all cookies". Point out the error and rewrite it.
Show answer
Error: APP_SSO_TOKEN, injected by the native app, would be cleared too, and the WebView loses the ability to SSO again; the user inside the app is pushed to the web login screen, the experience breaks, and it may even count as a reverse security bug (forcing password entry inside a WebView). Rewrite: "When an /api/s/* API returns 401, the UI clears the cookies sid, xsrf, uid, sid_stepup (if present) and all of sessionStorage. Do not clear APP_SSO_TOKEN (managed by the app). Then: if the UA matches the app WebView → call POST /auth/app/login; otherwise → go to /auth/web/login."
- An attacker sets up the page
evil.net, spoofs the ACME Trade App UA and callsPOST /auth/app/loginon the portal. What is the result? Why?
Show answer
First, a real browser does not let JS change the UA of a fetch request, so the feasible scenario is the attacker using a tool (curl) with a spoofed UA. The BFF sees a matching UA and continues, but the request has no valid APP_SSO_TOKEN cookie (the attacker does not have one, because the token is issued by the app to the real user and is host-only for the portal) → the SSO Token Verify API rejects it → 403. The attacker gets no session. This illustrates the principle: the UA only chooses the path; the right to a session comes from token verification + the account type check. The spec records the UA as a pre-check for early rejection and logging, not a security layer.
- The UI and the BFF share an origin so no CORS is needed. If the UI moves to
app.example.comtomorrow, what must change in the cookie and CORS spec?
Show answer
(1) CORS: the BFF must return Access-Control-Allow-Origin: https://app.example.com (not *) and Access-Control-Allow-Credentials: true; the UI fetches with credentials: 'include'; preflight OPTIONS must be handled for the X-XSRF-TOKEN header. (2) Cookies: the host-only sid on portal.example.com is still sent when app.example.com fetches the portal because the cookie belongs to the target domain, and app.example.com ↔ portal.example.com are same-site so Lax does not block it. But JS on app.example.com cannot read the xsrf cookie of portal.example.com (different origin) → the cookie-based synchronizer token collapses; the token must move to the response body/header. (3) The successUrl rule "same origin as the BFF" must be extended to an allow-list including app.example.com. This is a design change and needs its own spec.
Hands-on Exercises
Exercise 1: Redraw the map from memory
Close the lesson and redraw the diagram from section 2 on paper or in ASCII. Mark: (a) where IdP tokens exist, (b) where session ids exist, (c) which components are not exposed to the internet.
Expected output: a diagram with all 5 /auth/* entry points, Redis, the API Gateway; tokens appear only in the BFF and Redis.
Exercise 2: Apply the three questions to a system you know
Pick an application with login that you have built (or used). Fill in a 3-row table: Q1/Q2/Q3. Mark which cells you cannot answer.
Expected output: a 3-row table; at least one "don't know" cell turned into a concrete question for the development team.
Exercise 3: Find the flaws in a spec excerpt
What is missing from the following spec excerpt? Rewrite it completely.
"After the IdP redirects back to
/auth/web/login-callback, the BFF exchanges the code for tokens, creates a session and redirects to successUrl. On error, show the error screen."
Expected output: a rewrite with at least 5 error branches, each stating which session is deleted, whether cookies are set, and which screen.
Exercise 4: Redirect chain table from memory
Without looking at section 3, rewrite the 4-hop Web login table (From / To / Status / Cookies set / Cookies read). Then add a hop for the "wrong state" error branch.
Expected output: a 5-row table; the error row states that SessionID1 is deleted and the redirect goes to the "Login failed" screen.
Exercise 5: Write the normalizeSuccessUrl function and tests
Write the function from section 4 in TypeScript. Write tests for these inputs: a valid same-origin URL; https://portal.example.com.evil.net/; http://portal.example.com/; //evil.net/; a string that is not a URL; empty.
Expected output: 6 passing tests; all three attack cases return https://www.example.com/.
Exercise 6: Observe with curl
Using any demo IdP (or a mock), run curl -v -c cookies.txt against an endpoint that returns 302 and observe the Set-Cookie and Location headers. Then run curl -v -b cookies.txt against the Location and see which cookies are sent.
Expected output: a short note: cookies for a different Domain are not sent; curl's -L follows redirects automatically but needs -c/-b to carry cookies.
Exercise 7: Write the parameter table for POST /auth/app/login
Based on section 6, write the Item/Location/Required/Rule table for the app SSO endpoint: the APP_SSO_TOKEN cookie, the User-Agent header, no body. Give the error code for each violation.
Expected output: a table with ≥ 3 rows; UA mismatch → 403; missing token → 403; token verification fails → 403.
Exercise 8: Cookie table from memory
Rewrite the table from section 3 (6 cookies × 6 attributes, including the 5 cookies issued by the BFF and APP_SSO_TOKEN injected by the app) without looking at the lesson. For each Secure/HttpOnly/SameSite cell, write one sentence of reasoning.
Expected output: a complete table; the reasons for xsrf not being HttpOnly and sid having no Expires match sections 3.1 and 2.3.
Exercise 9: Try SameSite with two local origins
Run two local servers on localhost:3000 and 127.0.0.1:3001 (different sites). Server A sets a SameSite=Lax cookie and a SameSite=Strict cookie. From a page on B, create (a) an <a href> link to A, (b) a form POST to A, (c) a fetch to A. Observe DevTools → Network → Cookies.
Expected output: a 3-row × 2-column (Lax/Strict) table recording whether each cookie is sent; Lax is only sent in (a).
Exercise 10: Write the cookie section of the spec for sid_stepup
Following the template in section 7, write all 12 lines for sid_stepup. The "Set when"/"Deleted when" lines reference /auth/stepup/start and /auth/stepup/callback (or /auth/stepup/mfa-callback with context security-setting).
Expected output: a 12-line spec block; "Deleted when" includes both a successful callback and a failed callback.
References
- OAuth 2.0 for Browser-Based Apps (IETF draft)
- OAuth 2.0 Security Best Current Practice — RFC 9700
- OWASP Session Management Cheat Sheet
- Auth0: Backend For Frontend pattern
- RFC 9110 — HTTP Semantics (status codes)
- RFC 6749 §4.1.3 — Access Token Request (form-urlencoded)
- OWASP Unvalidated Redirects and Forwards Cheat Sheet
- MDN — Redirections in HTTP
- NestJS — Middleware and body parser
- RFC 6265bis — Cookies: HTTP State Management Mechanism (draft)
- MDN — Set-Cookie
- MDN — SameSite cookies
- OWASP Session Management Cheat Sheet — Cookies
- web.dev — Understanding "same-site" and "same-origin"