Identity and authorization
Connect an existing authentication and authorization system through Transport, Endpoint, and Service Middleware.
The Univer Collaboration SDK does not define users, roles, or an ACL model. An application establishes trusted identity in Transport Middleware and then protects realtime Sessions and authoritative collaboration data with Endpoint and Service Middleware.
This page applies Middleware and Events to one concrete task: integrating identity and authorization through Middleware.
Verify permissions
Run pnpm example:permissions, open http://127.0.0.1:3010, and try three accounts in turn:
- As Bob, change a cell.
- Switch to Casey. Verify that the change is visible and the cell is read-only.
- Switch to Dana. Verify that you cannot open the document.
Identity model
| Identifier | Provider | Meaning and lifetime |
|---|---|---|
userID | Application | Stable business identity and author of confirmed changesets |
memberID | Endpoint | Online member ID for one WebSocket Session; changes after reconnection |
sid + reqId | Client | Changeset submission identity that remains stable across retries |
User profile fields submitted by the browser, memberID, and revisions cannot substitute for application authentication. An application maps its stable user key to context.userID.
Establish identity in Transport Middleware
The Transport runs Middleware for every Collaboration HTTP request. An application can read a Cookie, a Session, or a Bearer token and attach the authenticated result to Context:
transport.use(async (context, next) => { const user = await auth.requireUser(context.incomingMessage); context.userID = user.id; context.customData.user = user; context.customData.tenantID = user.tenantID; context.customData.traceID = readTraceID(context.incomingMessage); await next();});When authentication fails, end the HTTP response without calling next():
transport.use(async (context, next) => { const user = await auth.findUser(context.incomingMessage); if (!user) { context.response.statusCode = 401; context.response.end("Authentication required"); return; } context.userID = user.id; await next();});The SDK does not prescribe Cookie names, token formats, user tables, or login flows.
How identity enters a WebSocket Session
The WebSocket path does not trust the user fields in client payloads. The Endpoint carries an authenticated HTTP Context into a realtime Session by means of a one-time Session Ticket:
Session Ticket HTTP request → Transport Middleware authenticates → Endpoint stores { userID, customData } → returns opaque one-time ticket → WebSocket open consumes ticket → creates Session { userID, memberID, customData }The ticket string contains neither userID nor customData. memberID identifies only the current connection, and it is not an independent identity credential. In a multi-node deployment with a shared ticket store, the stored customData is serialized, so it must remain JSON-serializable.
Authorize at the correct boundary
| Behavior to protect | Middleware |
|---|---|
| Collaboration HTTP entry | Transport use() |
| WebSocket connection | Endpoint connect |
| Joining a Unit Room | Endpoint joinUnit |
| Reading Snapshots, Blocks, or Changesets | Service readUnitData |
| Submitting content edits | Service submitChangeset |
| Creating a Unit | Service createUnit |
| Deleting Units | Service deleteUnits |
| Recovering Units | Service recoverUnits |
Endpoint joinUnit only controls whether a Session can enter a realtime Room. Snapshots and missing changesets can be read directly over HTTP, so a JOIN check cannot replace readUnitData. Likewise, a read-only client UI is a product hint and does not replace the submitChangeset policy on the server.
Protect read, JOIN, and edit
import { CollabError } from "@univerjs-pro/collaboration-service";endpoint.use("joinUnit", async (context, next) => { const allowed = await acl.canRead(context.session.userID, context.unitID); if (!allowed) { throw new CollabError("PERMISSION_DENIED", "Cannot join this Unit"); } await next();});service.use("readUnitData", async (context, next) => { const allowed = await acl.canRead(context.userID, context.request.unitID); if (!allowed) { throw new CollabError("PERMISSION_DENIED", "Unit is not accessible"); } await next();});service.use("submitChangeset", async (context, next) => { const unitID = context.request.changeset.unitID; const allowed = await acl.canEdit(context.userID, unitID); if (!allowed) { throw new CollabError("PERMISSION_DENIED", "Unit is read-only"); } await next();});This policy requires edit access for every changeset. If viewers can comment, use isCommentOnlyChangeset() as in the server example to authorize comment anchors separately.
Sheet mutation checks
The submitChangeset policy authorizes each changeset once. With mutation apply interception enabled, the server also validates individual sheet mutations, including freeze, gridlines, row and column visibility, sheet insertion and copy, and protection changes, and rejects the whole changeset when one of them exceeds the caller's permission points. Enable interception with the enableMutationApplyInterceptor option of UniverCollaborationServerPlugin, or with ENABLE_MUTATION_APPLY_INTERCEPTOR=true in the environment.
Protect Unit lifecycle
The collaboration protocol opens Units that already exist. “Create document” is normally an application API that writes a product record and an ACL before it calls createUnitFromData() or createUnitFromSnapshot(). The lifecycle also requires Service Middleware protection:
service.use("createUnit", async (context, next) => { if (!(await acl.canCreate(context.userID, context.request.snapshot.type))) { throw new CollabError("PERMISSION_DENIED", "Unit creation denied"); } await next();});service.use("deleteUnits", async (context, next) => { for (const unitID of context.request.unitIDs) { if (!(await acl.canDelete(context.userID, unitID))) { throw new CollabError("PERMISSION_DENIED", `Cannot delete ${unitID}`); } } await next();});Protect recoverUnits separately. A user who once had delete permission does not necessarily retain recovery permission.
Reuse lookups through customData
Middleware within the same Service call can use customData to avoid duplicate queries:
service.use("submitChangeset", async (context, next) => { const unitID = context.request.changeset.unitID; context.customData.role ??= await acl.getRole(context.userID, unitID); if (context.customData.role === "viewer") { throw new CollabError("PERMISSION_DENIED", "Unit is read-only"); } await next();});customData belongs only to the current call or Session and is not persisted automatically. Roles, ACLs, and tenant relationships remain in application storage.
Extension modules need separate policy
History, Thread Comment, Worktree, File, and Exchange each have their own Service Middleware:
- History list and changeset reads should check that the caller can read the Unit.
- Comment list should check read access, while add, reply, edit, and delete apply Comment policy.
- Worktree requires separate checks for visibility, draft edits, status changes, and merge.
- A Worktree merge into the trunk still goes through the trunk Service Middleware.
- File
uploadshould check edit access to the target Unit, whilesignUrlanddownloadcheck read access. - Exchange
importandexportare the appropriate place for quota checks and for checks on access to the source Unit; creating the imported Unit and reading the exported Unit still go through the Core Service Middleware.
Rules installed on the core Collaboration Service do not automatically protect these modules. The same application policy service should be reused rather than a separate ACL data model built for each extension.
Set the current user in the client
UserManagerService.setCurrentUser() sets the user ID, name, and avatar for the current Univer instance, and frontend components read these values from there. The “Concern me” filter of the comment panel, for example, uses this user ID to display the comments that involve the current user.
Call it after the Univer instance is created and before the document is loaded:
import { UserManagerService } from "@univerjs/core";// currentUser is your application profile; id/name/avatar are example field names.univer .__getInjector() .get(UserManagerService) .setCurrentUser({ userID: currentUser.id, name: currentUser.name, avatar: currentUser.avatar ?? "", });Map the application's stable user ID to userID and keep it identical to the authenticated context.userID on the server. The member names and avatars shared during collaboration are set in the server's connect Middleware, as described in Presence.
The Permissions example is the complete runnable version.
How is this guide?