LangChain4j Multi-User Isolation: Tokens, Parent Accounts, and a Three-Part Memory Key
Multi-tenant AI chat apps need to namespace conversation memory per user and enforce ownership on every request, or one user's history leaks into another's. This tutorial's three-part key plus server-side lookup is a concrete pattern to prevent that, and its use of a generic error message shows a security practice many APIs skip.
Ziwen, a LangChain4j-based AI homework helper, upgrades from a single-user app to a family one. v0.5 introduces parent registration and login, child profiles, and multiple chat windows per child. The database now has three tables: parent_account (with BCrypt-hashed passwords), child_profile (linked to parent), and chat_window (linked to child). Authentication uses a random token stored in Redis with a 7-day sliding expiration, returned via the Authorization header.
The core lesson is that isolating chat memory is simply a matter of key design. Memory in LangChain4j is stored per @MemoryId value, and Ziwen changes that to a three-segment key: parentId:childId:windowId. The server constructs this key only after verifying that the given windowId belongs to the authenticated parent, following the chain window -> child -> parent. Any mismatch returns the same "No such window" message, preventing enumeration of other users' windows. The tutorial also covers a lightweight approach: no full Spring Security, just a BCrypt hasher and an interceptor that protects all /api/** paths, with a whitelist for register/login/logout.
The verification section includes tests for duplicate registration, anti-enumeration, 401 on unauthenticated access, memory isolation between children and windows, and cross-family access denial. The package structure is organized into auth, ai, and common packages with one-way dependencies.
The article's central claim that memory isolation is just key granularity is correct, but the hard part is ensuring the key is built from trustworthy data; Ziwen does this by never trusting client-supplied parent or child IDs.
Using a single generic error message for both non-existent and forbidden resources prevents attackers from probing which window IDs exist, a practice often overlooked in REST APIs.
The tutorial's choice to skip Spring Security for a simple interceptor shows that framework weight can be unnecessary for basic auth; a hasher and a handler method suffice.
The three-part key is easy to reason about, but it works only because the server-side ownership check is airtight; any bug there would leak memory across families.