跪拜 Guibai
← Back to the summary

LangChain4j Multi-User Isolation: Tokens, Parent Accounts, and a Three-Part Memory Key

AI Knows Which Child It's Talking To (Multi-User Isolation and Token Authentication)

Series part 5 | Corresponding git tag: v0.5 | Prerequisite: v0.4 After this part, each child's chat histories stay separate; more importantly, you understand the truth about memory isolation: it's just a key namespace. Source code: https://github.com/tongli99/ziwen, tag v0.5 — after clone, git checkout v0.5, or browse the v0.5 snapshot.

Opening: The younger child continues chatting, but the AI remembers the older child's words

At the end of v0.4, Ziwen had only one user: you. The @MemoryId was a hand-written string; whoever opened the page chatted with the same memory. The younger child continued the older child's conversation, and the AI picked up the older child's last line—it's not that the model has a good memory, it's that two conversations were written into the same key.

This part does two things: give the app a parent account (registration, login, token), and support multiple children chatting at the same time.


I. Parent registration, with children and windows under the account

This version upgrades the app from "single-user" to "family-use." Parents register with a username and password to log in; children don't register separately—they are just nicknames under a parent's account; a child can open multiple chat windows, each with its own independent memory. In terms of data, there are three tables:

-- Parent account: passwords store only the BCrypt hash
CREATE TABLE IF NOT EXISTS parent_account (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    username      TEXT NOT NULL UNIQUE,
    password_hash TEXT NOT NULL,
    created_at    TEXT NOT NULL DEFAULT (datetime('now'))
);

-- Child profile (a sub-account under a parent): only a nickname
CREATE TABLE IF NOT EXISTS child_profile (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    parent_id  INTEGER NOT NULL,
    nickname   TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (parent_id) REFERENCES parent_account(id)
);

-- Chat window (a child can open multiple): each window has its own memory
CREATE TABLE IF NOT EXISTS chat_window (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    child_id   INTEGER NOT NULL,
    title      TEXT NOT NULL DEFAULT 'New chat',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (child_id) REFERENCES child_profile(id)
);

Three tables form a chain: parent 1→N children 1→N windows. The memory key parentId:childId:windowId in Section IV is built along this chain.


II. Registration and login

Authentication uses only one BCrypt hasher (from spring-security-crypto), without pulling in the full Spring Security stack—"registration/login + interceptor" doesn't need the entire filter chain. The complete registration sequence:

mermaid-diagram-2026-11-26-214203.png

In one sentence: the password is BCrypt-hashed and stored; if the username collides with the UNIQUE constraint, return "username already registered"; upon success, a token is issued, so registration is effectively login.

Login is symmetric, only missing the insert step and adding a password check; on failure it returns only "wrong username or password"—"user does not exist" and "wrong password" are not distinguished, to prevent attackers from enumerating registered usernames.

The token is a string of cryptographic random numbers; it carries no identity information itself. The mapping "token → parent id" is stored in Redis (key ziwen:auth:token:<token>, with a 7-day sliding expiration). The token is sent back via the Authorization: Bearer <token> header, and the frontend stores it in localStorage.


III. Interceptor: all APIs require login, pages are freely viewable

The division of labor between registration and the interceptor:

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(authInterceptor)
            .addPathPatterns("/api/**")
            .excludePathPatterns("/api/auth/register", "/api/auth/login", "/api/auth/logout");
}

All /api/** paths require login; the whitelist contains only register, login, and logout. Static pages (login.html, index.html) are not under /api, so they can be opened without login—you have to see the login page before you can log in. This is a common "pages reachable, APIs protected" layout: without a login, the app opens, the page renders normally, the first API request returns 401, and the frontend redirects to the login page.

The interceptor itself:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    String token = bearerToken(request);
    Long parentId = token == null ? null : tokenService.parentIdOf(token);
    if (parentId == null) {
        throw new UnauthorizedException();
    }
    request.setAttribute(AuthAttributes.PARENT_ID, parentId);
    return true;
}

After validation, the parent id is placed into a request attribute, which downstream controllers retrieve via @RequestAttribute. Downstream code thus never gets identity from request parameters: the parent id comes only from the login state, and a frontend cannot forge another parent by passing parameters.


IV. sessionId as a three-part key: isolation is just a key namespace

Parent A could call an API with parent B's windowId—request parameters can be any number.

The solution is to upgrade the memory key to three parts, with a single entry point for construction:

public String sessionIdOf(long parentId, long windowId) {
    WindowRow window = requireOwnedWindow(parentId, windowId);
    return parentId + ":" + window.childId() + ":" + windowId;
}
Key segment Content Who decides
parentId parent id login state (from token, cannot be forged)
childId child id server looks up from the window row (not from frontend)
windowId window id the only segment the frontend supplies

The chat request body contains only windowId; there is no childId and no parentId—the frontend only reports the window, and the server fills in the other two segments itself. Ownership verification is hidden inside requireOwnedWindow, which looks up three layers: window → child → parent:

private WindowRow requireOwnedWindow(long parentId, long windowId) {
    WindowRow window = findWindowRow(windowId)
            .orElseThrow(() -> new BizException("No such window"));
    ChildRow childRow = findChildRow(window.childId())
            .orElseThrow(() -> new BizException("No such window"));
    if (childRow.parentId() != parentId) {
        throw new BizException("No such window");
    }
    return window;
}

Any mismatch returns the same "No such window" message—the same idea as login anti-enumeration: don't leak "this window exists but isn't yours." Cross-family ID mixing is more serious than sibling mixing, and it is blocked here.

The constructed sessionId is handed to @MemoryId. The full chain for a single chat:

mermaid-diagram-2026-11-26-214250.png

Memory isolation, in short, is whether the key is fine-grained enough. LangChain4j's conversation memory stores keys by the value of @MemoryId. In Redis, the shape is visible:

ziwen:chat:memory:1:1:1   -- parent 1, child 1, window 1
ziwen:chat:memory:1:1:2   -- parent 1, child 1, window 2 (second window of the same child)
ziwen:chat:memory:1:2:3   -- parent 1, child 2, window 3 (the younger child's window)

V. How to organize the code: three peer packages, auth, ai, common

With more authentication code, the package structure coalesces into three peer modules:

com.tong.ziwen
├── ZiwenApplication        -- main class in root package: @SpringBootApplication scans only the root package and subpackages
├── auth/                   -- who is using it: registration/login, token, interceptor (controller / service / model)
├── ai/                     -- what it's for: companion reading, child profiles, poetry, new characters (controller / service / dto / config / store / tool)
└── common/                 -- common foundation: Response, AuthAttributes, exceptions and global handling

Two rules. Dependencies are one-way: auth→common, ai→common; auth and ai do not know each other—auth's interceptor throws UnauthorizedException, and common's GlobalExceptionHandler converts it to 401; putting exception classes in common prevents common from depending on anything. Separation of concerns: AccountService manages "who is using it" (account, password, token); UserService manages "who it serves" (child profiles, windows, sessionId). Neither grows into the other.


Acceptance testing

http/user.http has 19 steps ready, with tokens chained via REST Client variables (the registration response script stores the token, and subsequent requests automatically include Authorization: Bearer {{token}}). Criteria are judged by responses and Redis:

Test case Operation Expected
Duplicate registration Register the same name twice Second time: code=1 "username already registered"
Anti-enumeration Login with wrong password "Wrong username or password", same as when user doesn't exist
Not logged in Call GET /api/children without a header HTTP 401
Two-child isolation Each child chats a round, switch back to the older child Older child's memory remains, none of the younger child's
Same-child window isolation Say something in window one, ask in window two Window two knows nothing
First-question auto-title After a window sends a message, check the window list Title changes from "New chat" to the start of the question
Cross-family ID mixing Pass a windowId from another family "No such window"
See it in Redis KEYS ziwen:chat:memory:* Three-part keys like 1:1:1, 1:1:2
Restart the service Repeat "switch back to older child and ask" Memory persists (Redis persistence)
Logout Logout and then call a business API 401 (token deleted, no need to wait for expiry)

Parent accounts and child profiles are created in the UI itself: register/login, give the two children nicknames, and walk through the scenarios in the acceptance table one by one.

The frontend pages are shown below:

image-5.png

image-4.png