Repository navigation
[Design Discussion] Backend for Frontend (BFF) for browser-based applications #5699
UdeshAthukorala
started this conversation in
Design
Replies: 3 comments
|
Hi @UdeshAthukorala , For stateless sessions, how do we ensure that back-channel logout is enforced consistently across all BFF replicas? If the logout notification reaches one replica but a subsequent request is handled by another replica, could the session remain usable until token expiry? Should the shared ended-session store be a mandatory production configuration for multi-replica deployments rather than an optional enhancement? |
0 replies
|
Hi @UdeshAthukorala |
0 replies
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Related feature issue
Specifications this design follows:
Problem summary
How the ThunderID Console, SDKs and samples work today
@thunderid/browser,react,vue,react-router,tanstack-routersessionStorageby defaultsessionStorage@thunderid/express,node@thunderid/nextjs,nuxtsessionStoragesessionStorageSo we already have BFF code, but only for server-rendered apps. A SPA has no BFF option.
The two SPA modes
A SPA built with
@thunderid/browser,@thunderid/reactor@thunderid/vueruns in one of two modes.Redirect mode (the SPA has an OAuth client id):
Embedded mode (the SPA has an application id; the quickstarts' default):
/flow/executedirectly and renders each step of the sign-in flow.In both modes:
sessionStorageby default, orlocalStorage, or memory.What is wrong with that
What the RFC says
RFC 10017 describes three patterns:
The table above maps each ThunderID SDK and app to these patterns. Everything in the browser is pattern 6.3. The server SDKs are pattern 6.1.
Comparison
High-level approach
The one decision everything else follows from:
Three parts:
/api/auth. Cookie rules. Security rules. A conformance test suite.@thunderid/bffNode server for static SPAs. A Gothunderid bffcommand shipped in the ThunderID distribution, built in the same repo as the server. And the ThunderID server itself as the BFF for Console, which is how Console gets single logout.backendoption in@thunderid/browser. When set, the client calls the BFF endpoints instead of ThunderID. It never holds a token. The React and Vue components do not change.New surface
docs-internals/bff/spec.mdandthreat-model.md: the contract.docs-internals/sdk-development/spec.md: thebackendoption and the BFF handlers as SDK contract items.tests/bff-conformancein the thunderid repo: a test suite that takes a BFF URL and a ThunderID URL.@thunderid/express: the missing handlers (session,user,meta,refresh, the API proxy) and an encrypted stateless session as an alternative to the store.@thunderid/nextjsand@thunderid/nuxt: encrypted cookie,__Host-prefix, endpoint names aligned to the contract.@thunderid/browser: thebackendoption and a second transport behind the existing client interface.@thunderid/bff: a standalone Node server and Docker image.backend/cmd/bff: the Go implementation, shipped in the ThunderID distribution asthunderid bff. One binary, configured by environment variables, no Node runtime.backendmode on a hosted BFF inside the ThunderID server, with an in-process listener for ended sessions, so Console gets single logout.Out of scope
Architecture overview
Current
flowchart LR subgraph Browser SPA["SPA<br/>@thunderid/react or vue"] ST["sessionStorage<br/>access, refresh, ID token"] SPA --> ST end SPA -- "authorize, token, refresh" --> TID["ThunderID"] SPA -- "Bearer token<br/>needs CORS" --> API["APIs"]Proposed
flowchart LR subgraph Browser SPA["SPA<br/>@thunderid/react or vue<br/>backend mode"] CK["Cookie<br/>HttpOnly, encrypted<br/>no token readable by JS"] end subgraph "Same origin" BFF["BFF<br/>/api/auth/*<br/>confidential client"] end SPA -- "same-origin calls<br/>with cookie" --> BFF BFF -- "code exchange, refresh,<br/>flow/execute, token exchange" --> TID["ThunderID"] BFF -- "Bearer token" --> API["APIs"] TID -- "back-channel logout" --> BFFWalkthrough: sign in with the redirect flow
sequenceDiagram participant B as Browser (SPA) participant F as BFF participant T as ThunderID B->>F: GET /api/auth/signin F->>F: create state and PKCE verifier,<br/>set temp cookie F-->>B: 302 to ThunderID authorize B->>T: authorize T-->>B: sign-in page, user signs in T-->>B: 302 to /api/auth/callback?code B->>F: GET /api/auth/callback?code F->>T: token request (code, verifier, client secret) T-->>F: access, refresh, ID token F->>F: encrypt tokens into the session cookie F-->>B: 302 to the app, Set-Cookie B->>F: GET /api/auth/session F-->>B: { isSignedIn: true, user }Walkthrough: sign in with the embedded flow
sequenceDiagram participant B as Browser (SPA with SignIn component) participant F as BFF participant T as ThunderID B->>F: POST /api/auth/flow { step input } F->>T: POST /flow/execute with Flow-Secret header T-->>F: next step, or assertion when done F-->>B: next step (no secret, no token) Note over B,F: repeat until the flow is complete F->>T: exchange assertion for tokens F->>F: encrypt tokens into the session cookie F-->>B: { success: true }Walkthrough: an API call
sequenceDiagram participant B as Browser (SPA) participant F as BFF participant A as API B->>F: GET /api/orders (cookie, X-Requested-With) F->>F: decrypt cookie, check Origin F->>F: refresh the access token if it is about to expire F->>A: GET /orders, Authorization: Bearer A-->>F: 200 F-->>B: 200Walkthrough: logout from another app
sequenceDiagram participant O as Other app participant T as ThunderID participant F as BFF participant B as Browser (SPA) O->>T: sign out T->>F: POST /api/auth/backchannel-logout (logout_token) F->>F: validate token, record the ended session F-->>T: 200 B->>F: next call, or /api/auth/session on tab focus F-->>B: { isSignedIn: false } B->>B: show the signed-out state/api/auth/sessionwhen the tab gets focus.Key design decisions
SameSite=Laxplus an Origin check plus a required custom headerbackendoption on the existing client. Same interface1. The contract
All endpoints are same-origin, under one prefix. Default prefix:
/api/auth.GET /signinGET /callbackPOST /flowGET /session{ isSignedIn, user, expiresAt }. Never a tokenGET /user/users/mePATCH /user/profilePATCH /user/credentialsGET /metaPOST /signoutPOST /refreshtoken.get)ANY /proxy/*POST /backchannel-logoutRules:
Cache-Control: no-store.code, like the SDK errors.2. Session model
Stateless (default)
A256GCM, with a documented claim set (sub,sid,sessionId,signedInAt,accessToken,idToken,expiresAt).THUNDERID_SESSION_SECRET, at least 32 bytes.Path=/api/auth/refresh. It travels only to that endpoint. This also keeps the main cookie small.What stateless cannot do alone
For these there is an optional store:
get,setwith a lifetime).Does single logout need a stateful session?
No. "Stateless" means the tokens live in the cookie, not in a server store. It does not mean the server remembers nothing.
abcended" until the browser's next request.So the honest statement is: stateless sessions, plus a small, short-lived list of ended sessions. That is still far from stateful:
Without the list, logout still happens, only later:
The list makes logout immediate. The fallback makes it eventual. The design ships the list and documents the fallback.
Stateful (switch)
@thunderid/expressdoes today.flowchart TB subgraph Stateless C1["Cookie: encrypted tokens"] --> R1["Any replica"] R1 -.-> S1["Optional store:<br/>ended sessions, idle timeout"] end subgraph Stateful C2["Cookie: session id"] --> R2["Any replica"] R2 --> S2["Required store:<br/>tokens and session"] end3. Cookies and CSRF
Cookie attributes:
Secure,HttpOnly,Path=/.__Host-. Then the cookie cannot be set from a subdomain or with aDomainattribute.SameSite=Lax.Why not
SameSite=Strict:/api/auth/callback.Strict, the browser does not send our temp cookie on that request.stateand the PKCE verifier. Sign-in fails.Laxsends the cookie on top-level navigations, so the callback works.CSRF defence, three layers:
SameSite=Lax. A cross-sitePOSTdoes not carry the cookie.Origin(orSec-Fetch-Site) header with its own origin.X-Requested-With: thunderid, on every call the SDK makes. A cross-site page cannot send it without a CORS preflight, which the BFF refuses.4. Sign-in
stateare created on the server and kept in a short-lived temp cookie. Same as Nuxt and Next.js today./api/auth/flow. The BFF adds the Flow Secret and calls/flow/execute. The browser never sees the secret.SignInandSignUpcomponents work the same way as now. Only the URL they post to changes.5. Calling APIs
Two ways, both without a token in the browser:
protect()-style check. The RFC allows the BFF to be the resource server (section 6.1.2.5). This is the simplest and most common setup./api/auth/proxy/<target>attaches the access token and forwards. Targets are an allow list in the configuration, never a URL from the browser.Third-party APIs:
getAccessToken()in the browser SDK:backendmode.6. Logout and timeouts
POST /api/auth/signout. The BFF revokes, clears the cookies, and returns the ThunderID logout URL. The SDK navigates there, so the ThunderID session ends too.isSignedIngoes false on the next call. The SDK also calls/api/auth/sessionwhen the tab gets focus, so an open tab notices soon.How the BFF handles a back-channel logout
End to end:
sequenceDiagram participant O as Other app participant T as ThunderID participant F as BFF participant L as Ended-sessions list<br/>(memory or Redis) participant B as Browser (SPA) Note over B,F: Earlier: user signed in. Cookie holds sid = abc. O->>T: user signs out (or admin ends the session) T->>T: end SSO session, revoke tokens T->>F: POST /api/auth/backchannel-logout<br/>logout_token (sid = abc) F->>F: validate the token<br/>(signature, iss, aud, typ, events, jti, no nonce) alt stateless mode F->>L: set "sid:abc", ttl = cookie lifetime else stateful mode F->>L: delete session abc from the store end F-->>T: 200 Note over B: Cookie is still in the browser B->>F: next request with cookie (sid = abc) F->>F: decrypt cookie F->>L: is "sid:abc" ended? L-->>F: yes F-->>B: { isSignedIn: false } B->>B: show signed-out stateInside the handler:
flowchart TD A["POST /api/auth/backchannel-logout"] --> B{"Form body with<br/>logout_token,<br/>under 16 KB?"} B -- no --> R400a["400"] B -- yes --> C{"Token valid?<br/>signature, iss, aud,<br/>typ = logout+jwt, events,<br/>jti, not expired, no nonce"} C -- no --> R400b["400<br/>ThunderID does not retry"] C -- yes --> D{"jti seen before?"} D -- yes --> R400c["400, replay"] D -- no --> E{"Session mode"} E -- stateless --> F["Record sid (or sub + iat)<br/>in the ended-sessions list<br/>ttl = cookie lifetime"] E -- stateful --> G["Delete the session<br/>from the store"] F --> H{"Write ok?"} G --> H H -- no --> R500["500<br/>ThunderID retries later"] H -- yes --> I["Remember jti"] I --> R200["200, Cache-Control: no-store"]Three things to notice:
7. The browser SDK in
backendmodeConfiguration:
What changes inside
@thunderid/browser:backendmodesignIn()/api/auth/signin, or posts flow steps to/api/auth/flowisSignedIn(),getUser()/api/auth/sessionand/api/auth/user, cached in memory, refreshed on tab focushttp.request()getAccessToken()signOut()/api/auth/signout, follows the returned URLsessionStorage,localStorage, memoryWhat does not change:
@thunderid/react,@thunderid/vue,@thunderid/react-router,@thunderid/tanstack-router.SignIn,SignUp,SignedIn,SignedOut,User,UserDropdown,UserProfile.How: the browser client already splits its work into helpers (
SPAHelper,AuthenticationHelper, the HTTP client, storage).backendmode is a second set of these helpers behind the same client. It is selected once, at initialization.8. Implementations
flowchart TB CT["BFF contract<br/>spec + conformance suite"] CT --> EX["@thunderid/express<br/>reference"] CT --> NX["@thunderid/nextjs"] CT --> NU["@thunderid/nuxt"] CT --> SA["@thunderid/bff<br/>standalone Node"] CT --> GO["thunderid bff<br/>Go, in the distribution"] CT --> HO["ThunderID server<br/>hosted BFF for Console"] CT -.-> SP["Spring Security, .NET<br/>native support, guide only"]@thunderid/expressand@thunderid/node@thunderid/nextjs,@thunderid/nuxtthunderid bff(Go)@thunderid/bffWhat every implementation shares:
THUNDERID_BASE_URL,THUNDERID_CLIENT_ID,THUNDERID_CLIENT_SECRET,THUNDERID_SESSION_SECRET,THUNDERID_FLOW_SECRET,THUNDERID_BFF_PREFIX,THUNDERID_BFF_PROXY_TARGETS.What each one keeps for itself:
The Go implementation
backend/cmd/bffin the thunderid repo. Built and released with the server.thunderid bff. Configured by the same environment variables as the Node implementations.golang.org/x/oauth2andcoreos/go-oidcorzitadel/oidc). The server is an OP, not an RP, so the server'sinternalpackages are not imported.9. Console and Gate
This section is in scope. It answers one question: how does the ThunderID Console get single logout (SLO).
Console today
@thunderid/reacton top of@thunderid/browser.sessionStorage./console.SLO today
Two directions:
sequenceDiagram participant O as Other app participant T as ThunderID participant C as Console (browser) O->>T: sign out T->>T: end SSO session, revoke tokens Note over C: Console still looks signed in C->>T: next API call T-->>C: 401 C->>C: now signed outConsole with the hosted BFF
backendmode. Its SDK wiring inwithConfig.tsxstays. The components stay.How the server learns about it:
TerminatedSessionevent for every ended session (see [Design Discussion] Support OIDC Back-Channel Logout #5258).sidin the same ended-sessions list the other BFF implementations use./sessioncheck on tab focus, returnsisSignedIn: false.sequenceDiagram participant O as Other app participant T as ThunderID server participant H as Hosted BFF (inside the server) participant C as Console (browser) O->>T: sign out T->>T: end SSO session T->>H: TerminatedSession event (in process) H->>H: record ended sid C->>H: next call, or /api/auth/session on tab focus H-->>C: { isSignedIn: false } C->>C: show the signed-in page as signed outWhat Console gains:
Trusted-issuer mode
/backchannel-logoutendpoint. This is the same receiver code the Gothunderid bffuses.Gate
/flowendpoint. This is optional and only for consistency.What this needs
backendmode. The trusted-issuer code path reviewed, since the BFF becomes the RP there.backendmode) and P6 (the Go implementation).10. Browser-only mode, in parallel
The browser-only mode stays for teams that cannot run a backend. It gets closer to the RFC floor:
@thunderid/browser. The server already supports DPoP.sessionStorageas an opt-in.11. Configuration
baseUrlTHUNDERID_BASE_URLclientIdTHUNDERID_CLIENT_IDclientSecretTHUNDERID_CLIENT_SECRETsessionSecretTHUNDERID_SESSION_SECRETflowSecretTHUNDERID_FLOW_SECRETbff.prefixTHUNDERID_BFF_PREFIX/api/authbff.modeTHUNDERID_BFF_MODEstatelessorstatefulstatelessbff.storebff.proxy.targetsTHUNDERID_BFF_PROXY_TARGETSsession.idleTimeoutTHUNDERID_SESSION_IDLE_TIMEOUT12. Observability
13. Failure modes
/sessionreturnsisSignedIn: false14. Conformance and parity
tests/bff-conformancein the thunderid repo./sessionand/user, refresh, proxy, sign-out, back-channel logout, a forged logout token, a replayed token, CSRF refusals, cookie attributes, no token in any response.15. Phasing
flowchart LR P0["P0<br/>Spikes,<br/>this discussion"] --> P1["P1<br/>Spec, threat model,<br/>conformance suite"] P1 --> P2["P2<br/>Cookie hardening<br/>Next.js, Nuxt"] P1 --> P3["P3<br/>Express reference<br/>BFF handlers"] P3 --> P4["P4<br/>Browser SDK<br/>backend mode + sample"] P3 --> P5["P5<br/>@thunderid/bff<br/>standalone Node"] P3 --> P6["P6<br/>thunderid bff<br/>Go, in the distribution"] P6 --> P7["P7<br/>Console on the<br/>hosted BFF, SLO"] P4 --> P7docs-internals/bffspec and threat model. SDK spec chapter. Conformance suite skeleton__Host-prefix. Can go first, it is independentsession,user,meta,refresh, proxy, encrypted stateless mode@thunderid/browserbackendmode. React quickstart "with BFF": Vite app plus Express BFF@thunderid/bffstandalone Node server, Docker image. In parallel with P6thunderid bffin Go, in the distribution. In parallel with P5Spikes before P1
backendtransport replacesLaxis needed for the callback. Confirm the embedded flow has no cross-site stepinternalAlternatives considered
A1: One Node package instead of a contract
A2: Stateful by default
A3: Signed cookie instead of encrypted
A4:
SameSite=StrictLaxplus an Origin check plus a required header.A5: Token-mediating backend
A6: A separate
@thunderid/browser-bffpackagebackendoption on the existing client.A7: Cross-origin BFF with CORS and credentials
Questions for community input
thunderid bffbinary: should it be a subcommand of thethunderidbinary, or a separate binary in the same distribution?Change logIS
All reactions