Authorization
A deep dive into designing a production-grade RBAC system — from permission evaluation engines and role hierarchies to component-level guards, API middleware, and admin panels. Covers everything you need to build authorization that scales.
We are building an RBAC (Role-Based Access Control) system — a permission management library that any application can integrate to control what users can see and do. Think of it as the authorization layer that sits between your UI components and your API routes, answering one question everywhere: is this user allowed to do this thing?
Every SaaS product above a certain scale needs this. GitHub has organization roles (owner, member, collaborator). Notion has workspace roles (admin, member, guest). Slack has channel-level permissions. The underlying engine is always the same: a permission evaluator that maps roles to actions, a set of component-level guards for the UI, and middleware for the API layer.
We will use the RADIO framework throughout this article: Requirements, Architecture, Data Model, Interface (API), and Optimization — covering every layer from the frontend React components to the backend middleware.
An RBAC system touches every part of the application — frontend rendering, API routes, WebSocket connections, and even background jobs. Before we design, we scope what the system must support and what we explicitly leave for future iterations.
Every RBAC system has exactly three core abstractions. Getting these right determines whether your authorization code is readable, testable, and auditable six months from now.
Resources are the things you protect: a project, a ticket, a comment, a user profile. Each resource has a name and optionally a scope — organization-level resources behave differently from project-level ones.
Actions are the operations on those resources:create, read, update, delete, and the catch-all manage that grants all four. The manage action is a design choice — some systems prefer explicit listing of every action.
Roles group permissions into reusable bundles. A viewer can read projects and tickets. An editor can also create and update tickets. An admin can manage everything. Roles form a hierarchy: an admin inherits everything an editor has, and an editor inherits everything a viewer has.
| Abstraction | Example | Who defines it |
|---|---|---|
| Resource | project, ticket, comment | Developer at code-time |
| Action | create, read, update, delete | System-defined |
| Role | viewer, editor, admin | Admin at runtime |
| Scope | org:acme, project:xyz | Admins at assignment-time |
The permission evaluation engine is the heart of the RBAC system. It receives a user ID, a resource, and an action, and returns a boolean. The entire UI and API authorization layers depend on this engine being correct, fast, and predictable.
The engine maintains an in-memory map of resource:action keys to sets of authorized user IDs. This is built once when the user logs in or when roles change, and then queried synchronously. No database calls during evaluation, no async overhead, zero network latency.
The can() method is a simple map lookup — O(1) on average. The canAny() and canAll() methods are convenience wrappers for checking multiple permissions in one call. This avoids multiple render passes in the UI when a component needs to check several permissions at once.
Auth layer resolves user identity and loads role assignments from DB.
Roles, permissions, and user assignments are loaded into the in-memory evaluator.
Parent roles are walked recursively and their permissions merged into the effective set.
Flattened to resource:action → Set<userId> for O(1) lookup.
UI calls can() / API calls requirePermission(). Synchronous check, no DB hit.
true → render component or process request. false → show fallback or 403.
Every permission check that hits the database adds 5-50ms of latency. In a typical page render, a dashboard might check 20+ permissions across different components. A 20× database waterfall would add 100-1000ms to the render time. With an in-memory evaluator, all 20 checks complete in under 5ms total.
The data model defines how roles, permissions, and user assignments are stored and related. A well-structured model is the difference between a system you can extend and one you need to rewrite.
Every RBAC system needs three tables in the database: roles, permissions, and user_roles. The roles table stores the role definition and its parent for hierarchy. The permissions table stores the resource-action pairs. The user_roles table is the many-to-many join that associates users with roles, optionally scoped to an organization or project.
The scope field on UserRole is the key to multi-tenant RBAC. A user might be an admin in one organization and a viewer in another. The evaluator filters permissions by the current scope context, ensuring that users never see or act on resources outside their authorized scope.
| Table | Columns | Purpose |
|---|---|---|
| roles | id, name, description, parent_role_id, is_system, created_at | Define role names and hierarchy |
| permissions | id, role_id, resource, action, conditions | Map resources and actions to roles |
| user_roles | user_id, role_id, scope_type, scope_id, granted_at, expires_at | Assign roles to users with optional scoping |
conditions field on permissions enables simple ABAC-like rules. For example, a permission with { department: 'engineering' } only applies when the user's department matches. Full ABAC engines like OPA or Casbin are more powerful but add significant complexity.The RBAC system has two API surfaces: the client-side permission hook that React components use, and the server-side middleware that protects API routes. Both are thin wrappers around the evaluation engine.
The client API exposes a React context that provides the evaluator and a set of hooks. The useCan() hook is the primary interface — it takes a resource and action, returns a boolean. Higher-level convenience hooks like useCanRead() and useCanManage() reduce boilerplate for common patterns.
The context wrapping is critical. It allows us to inject a mock evaluator in tests (same pattern as analytics SDK's factory) and to swap the evaluator implementation without changing every component that checks permissions.
On the server, the evaluator runs in request scope. Each HTTP request gets its own evaluator instance initialized with the authenticated user's roles. The evaluator is available in middleware, route handlers, and even background job processors.
Component-level guards are where RBAC meets the UI. We provide two patterns: a higher-order component (HOC) for wrapping entire pages or sections, and a declarative component for inline conditional rendering. Both use the same underlying hook.
The HOC is ideal for route-level protection. It wraps the entire component and shows nothing (or a fallback) if the user lacks permission. This is useful for admin pages, settings panels, and other feature-level gates.
The <Can> component is for inline use inside templates. It wraps a specific piece of UI — a button, a link, a table row action. The fallback prop provides a graceful degradation path: show a disabled button instead of hiding the action entirely.
Real applications need more than binary checks. An "export" button might require both read and export permissions. A "danger zone" section might be visible if the user has either manage or delete. We provide <IfAll> and <IfAny> for these cases.
| Pattern | Best For | Gotcha |
|---|---|---|
| HOC (withPermission) | Route-level guards, entire page sections | Cannot compose multiple checks easily |
| Declarative (<Can>) | Inline buttons, links, individual elements | Adds wrapper elements to the DOM tree |
| Composable (<IfAll>/<IfAny>) | Complex permission logic, multi-check gates | More verbose for single checks |
Rendering UIs based on permissions is more nuanced than it sounds. The naive approach — fetch permissions, then conditionally render — creates a flash of unauthorized content, followed by a re-render when permissions arrive. Users see a button appear or disappear after the page loads, which is jarring.
The solution is to gate permissions at the layout level, not the element level. Fetch all permissions for the current user once when the app boots, store them in the evaluator context, and let all downstream checks be synchronous. This means the first render already has the correct permissions — no flicker.
In practice, this looks like a <PermissionProvider> at the root of the app that fetches the user's effective permissions and initializes the evaluator before any child component renders. If permissions are loading, a skeleton or spinner is shown once. When they arrive, every <Can> on the page renders correctly on the first paint.
| Strategy | Pros | Cons |
|---|---|---|
| Client-side only | Simple, reactive, easy to test | Permissions visible in bundle, flicker possible |
| Server-side only (SSR/RSC) | Secure, no permission leakage in bundle | Harder to handle client-side interactions |
| Hybrid (recommended) | Best of both: server enforces, client convenience | Two permission sources must stay in sync |
API guards are where RBAC stops being a UI convenience and becomes a security boundary. Every server endpoint that handles sensitive data must independently verify that the requesting user has the required permissions — regardless of what the client UI shows or hides.
The guard is a middleware function that wraps the route handler. It extracts the user from the request context, checks the required permission against the evaluator, and either calls next() or returns a 403 response.
Check API key validity and IP allowlists. Reject obvious bad actors before they hit your origin.
Authenticate the user (JWT/session). Extract user ID and roles into request context.
Initialize evaluator with user's roles. Check resource:action. Return 403 if denied.
Only authorized requests reach here. Handler trusts the middleware chain.
Resource owners skip permission checks (you can always edit your own comment).
A common rule in SaaS products is: "you can edit your own content but not others'." This is ownership-based authorization, which complements role-based authorization. The ownership check happens first: if the resource belongs to the user, the action is permitted. If not, the role-based check applies. This pattern avoids needing granular per-resource roles.
The admin panel is the most permission-dense part of any application. It must let power users manage roles, assign permissions, and audit who has access to what — all while enforcing the same RBAC rules on itself.
The admin panel uses the same <Can> component as the rest of the app. This means the "Create Role" button is gated behind resource: 'user-management', action: 'create'. An admin who can manage roles sees the full interface. A support agent who can only view roles sees a read-only version.
Create, edit, delete roles. Set parent role for hierarchy. System roles are protected from deletion.
Grid view: resources vs actions. Checkboxes to assign permissions to roles with bulk operations.
Search users, assign roles with optional scope. Set expiration dates for temporary access.
Pick a user and see their resolved permission set after hierarchy resolution. Invaluable for debugging.
Every role creation, permission change, and user assignment is logged with timestamp and actor.
root or superadmin role should be the only one that can modify the permission system. Everyone else ( admin, manager ) sees a read-only or subset view. This prevents accidental lockout of the entire team.Role hierarchy is what makes RBAC scalable. Without hierarchy, every role must explicitly list every permission — creating a combinatorial explosion when you have viewer, editor, moderator, admin, and superadmin. With hierarchy, each role only defines its delta from the parent.
Each role has a parentRoleId that points to another role. When resolved, the evaluator walks up the hierarchy recursively, collecting permissions from each ancestor. The resolved permission set for a role is its own permissions merged with all inherited permissions. A role at the top of the hierarchy (parentRoleId: null) has no inheritance.
| Model | Description | When to Use |
|---|---|---|
| Flat (no hierarchy) | Each role defines all permissions explicitly | Simple apps with 2-3 roles, no inheritance needed |
| Single inheritance (chosen) | Each role has one parent. Permissions accumulate upward. | Most SaaS apps. Simple, predictable, easy to audit. |
| Multiple inheritance | Roles can inherit from multiple parents (union) | Complex orgs with matrix reporting. Rarely needed. |
When roles can have parents, circular references become possible:admin → editor → admin. The evaluator must detect and break these cycles during initialization. A simple visited-set during the recursive walk handles this — if we encounter a role already in the current ancestry chain, we stop and log a warning.
Performance is the primary concern for an RBAC system that runs on every render and every API call. Every microsecond spent checking permissions is a microsecond the user waits for their page to load.
The most impactful optimization is caching the flattened permission map for the duration of the user session. When a user logs in, load all their role assignments, resolve the hierarchy, and build the map once. Cache it in memory with a 5-minute TTL. When an admin changes a role's permissions, broadcast an invalidation event so active sessions re-fetch.
The useCan() hook should be memoized per (resource, action) pair. Without memoization, every render creates a new call to the evaluator — harmless for one check, but noticeable when a list of 100 items each checks a permission. A simple useMemo with resource and action in the dependency array prevents redundant evaluations.
| Strategy | Memory | Freshness | Complexity |
|---|---|---|---|
| No cache (DB per check) | None | Always fresh | Simple |
| Session cache (TTL) | Low — few KB per user | Stale up to TTL | Moderate — cache invalidation |
| Redis-backed global cache | Shared across servers | Sub-second invalidation | High — Redis infra + serialization |
For critical paths (the first page after login), prefetch the permissions map in parallel with the user data. Most RBAC systems load permissions after authentication, creating a waterfall: auth → get user → get roles → get permissions. Prefetching collapses this into a single round-trip.
permissions field to the /me endpoint response. This eliminates the waterfall without adding any server complexity — the user query already joins the roles table.If you remember only a few things from this article, make them these:
Every database-backed permission check adds 5-50ms. With 20 checks per page, that is a 1-second render penalty. Load once, check in O(1).
Each role defines its delta from the parent. Flat permission lists explode combinatorially. Single inheritance covers 95% of real-world needs.
Every action must be authorized on the server independently. The <Can> component removes temptation, not access. Always guard the API.
Add permissions to the /me endpoint. This eliminates the auth → user → roles → permissions waterfall and saves hundreds of milliseconds.
withPermission for routes, <Can> for inline elements, <IfAll>/<IfAny> for complex gates. One library, three patterns, no friction.
5-minute TTL for session cache. Broadcast invalidation on role changes. Prefetch with user profile to avoid the waterfall.