Designing Role-Based Access Control for SaaS Applications
Roles map to permissions, permissions guard actions: an RBAC model that stays maintainable.
- rbac
- authorization
- security
- saas
On this page ยท 14 sections
Authorization bugs are quiet. Nothing crashes; a user simply sees or changes something they should not. Role-based access control (RBAC) gives a SaaS product a clear way to answer "may this user do this?" in one place instead of scattering if (user.role === "admin") through the codebase. This guide designs an RBAC system that stays maintainable as the product grows: roles that map to permissions, tenant-scoped memberships, reusable guards, ownership checks, auditing and a test matrix.
The model
- 1User
an identity
- 2Membership
a user's role inside one tenant
- 3Role
a named set of permissions
- 4Permission
a single action on a resource
- Permission: the unit your code checks, named
resource:action(for exampleinvoice:read,invoice:delete,member:invite). - Role: a bundle of permissions (
owner,admin,editor,viewer). - Membership: connects a user, a tenant and a role. The same person can have different roles in different tenants.
Step 1: Define permissions and roles in code
Keeping the matrix in code (version-controlled and reviewable) is a good start. Move it to the database only when customers need to define custom roles.
// src/authz/permissions.tsexport const PERMISSIONS = [ "invoice:read", "invoice:create", "invoice:update", "invoice:delete", "member:read", "member:invite", "member:remove", "billing:manage",] as const;export type Permission = (typeof PERMISSIONS)[number];export type Role = "owner" | "admin" | "editor" | "viewer";export const ROLE_PERMISSIONS: Record<Role, readonly Permission[]> = { viewer: ["invoice:read", "member:read"], editor: ["invoice:read", "invoice:create", "invoice:update", "member:read"], admin: [ "invoice:read", "invoice:create", "invoice:update", "invoice:delete", "member:read", "member:invite", "member:remove", ], owner: [...PERMISSIONS], // everything, including billing};export function can(role: Role | undefined, permission: Permission): boolean { if (!role) return false; // deny by default return ROLE_PERMISSIONS[role]?.includes(permission) ?? false;}The Permission type is a union of literal strings, so a typo like "invoce:read" is a compile error. The can function returns false for unknown or missing roles: deny by default.
Step 2: Store memberships, scoped to a tenant
CREATE TABLE memberships ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, role text NOT NULL CHECK (role IN ('owner', 'admin', 'editor', 'viewer')), created_at timestamptz NOT NULL DEFAULT now(), UNIQUE (user_id, tenant_id));CREATE INDEX memberships_tenant_idx ON memberships (tenant_id);Load the membership for the current user and tenant once per request and attach it to the request. Never read a single global users.role in a multi-tenant product.
Step 3: Guards that read like documentation
// src/authz/guards.tsimport type { NextFunction, Request, Response } from "express";import { AppError } from "../errors";import { can, type Permission } from "./permissions";export const requirePermission = (...needed: Permission[]) => (req: Request, _res: Response, next: NextFunction) => { const role = req.membership?.role; if (!req.user) return next(AppError.unauthorized()); if (!needed.every((p) => can(role, p))) return next(AppError.forbidden()); next(); };Routes now declare their requirements in one line:
router.get("/invoices", requirePermission("invoice:read"), listInvoices);router.post("/invoices", requirePermission("invoice:create"), createInvoice);router.delete("/invoices/:id", requirePermission("invoice:delete"), deleteInvoice);router.post("/members/invite", requirePermission("member:invite"), inviteMember);Adding a new role later changes the matrix, not these routes.
Step 4: Ownership and attribute rules
Some rules depend on the resource, not just the role: "an editor can update their own invoices, an admin can update any." Model that with a second permission and a resource-aware check:
// Add to the permission list: "invoice:update_any"export function canUpdateInvoice( member: { userId: string; role: Role }, invoice: { createdBy: string },): boolean { if (can(member.role, "invoice:update_any")) return true; return can(member.role, "invoice:update") && invoice.createdBy === member.userId;}async function updateInvoice(req: Request, res: Response) { const invoice = await invoices.findById(req.params.id!); // already tenant-scoped if (!invoice) throw AppError.notFound("Invoice"); // 404, do not reveal existence if (!canUpdateInvoice({ userId: req.user!.id, role: req.membership!.role }, invoice)) { throw AppError.forbidden(); } res.json(await invoices.update(invoice.id, req.body));}Keep these decisions in one policy module so rules live in a single place and are easy to test.
Step 5: Enforce in the service layer too
Route guards protect HTTP endpoints, but the same business operation might be reached by a background job, a webhook or a different route. Putting the check in the service makes it impossible to bypass accidentally:
class InvoiceService { async delete(actor: Actor, id: string) { if (!can(actor.role, "invoice:delete")) throw AppError.forbidden(); await this.repo.delete(id); await this.audit.record(actor, "invoice.deleted", { id }); }}Use route guards for early, cheap rejection and service checks as the authoritative rule.
Step 6: Surface permissions to the UI (but never rely on it)
Send the user's effective permissions with their session so the UI can hide controls they cannot use:
app.get("/me", (req, res) => { res.json({ user: { id: req.user!.id, name: req.user!.name }, tenant: req.tenant, role: req.membership!.role, permissions: ROLE_PERMISSIONS[req.membership!.role], });});This is for usability only. The server must re-check everything, because anyone can call the API without your UI.
Step 7: Keep role changes safe
- Last owner protection: prevent removing or demoting the final owner of a tenant.
- No privilege escalation: a user cannot grant a role higher than their own.
- Immediate effect: if roles are cached or placed in tokens, define how quickly changes apply. A short cache TTL or a "permissions version" claim that invalidates old tokens keeps stale access short-lived.
- Sensitive actions (billing, deleting the tenant, exporting all data) can additionally require recent re-authentication.
async function changeRole(actor: Actor, targetUserId: string, newRole: Role) { if (!can(actor.role, "member:remove")) throw AppError.forbidden(); if (rank(newRole) > rank(actor.role)) throw AppError.forbidden("Cannot grant a higher role than your own"); const target = await memberships.find(targetUserId, actor.tenantId); if (target?.role === "owner" && (await memberships.countOwners(actor.tenantId)) === 1) { throw AppError.badRequest("A tenant must always have at least one owner"); } await memberships.setRole(targetUserId, actor.tenantId, newRole); await audit.record(actor, "member.role_changed", { targetUserId, newRole });}Audit logging
Record who did what, to which resource, when and from where, especially for permission changes, deletions, exports and failed authorization attempts. Audit logs are how you answer "who removed that user?" and how you spot probing.
Custom roles
When customers need custom roles, move the role-to-permission mapping into tables (roles, role_permissions), keep permission names defined in code (so guards stay type-safe), and keep built-in roles read-only. Cache a user's effective permission set per request or for a short time so you do not query it for every guard.
Common mistakes
- Checking roles (
role === "admin") instead of permissions. - Enforcing only in the UI.
- A single global role for a multi-tenant user.
- Forgetting the ownership check, so any editor can edit anyone's record.
- Returning 403 for resources in other tenants, which confirms they exist.
- Letting users escalate roles, or leaving a tenant with no owner.
- Stale permissions cached in long-lived tokens.
Testing the matrix
Authorization is a table, so test it like one:
const cases: [Role, Permission, boolean][] = [ ["viewer", "invoice:read", true], ["viewer", "invoice:delete", false], ["editor", "invoice:create", true], ["editor", "invoice:delete", false], ["admin", "member:invite", true], ["admin", "billing:manage", false], ["owner", "billing:manage", true],];describe.each(cases)("%s / %s", (role, permission, expected) => { it(`is ${expected ? "allowed" : "denied"}`, () => { expect(can(role, permission)).toBe(expected); });});it("denies when there is no role", () => { expect(can(undefined, "invoice:read")).toBe(false);});Add endpoint tests that call routes as each role and assert 200 or 403, plus tests for ownership rules, last-owner protection, escalation attempts and cross-tenant access.
Best practices
- Name permissions
resource:actionand check permissions, not roles. - Deny by default.
- Scope roles to memberships, and enforce in both routes and services.
- Keep policy logic in one place with a test matrix.
- Audit permission changes and sensitive actions.
- Treat UI permission hints as convenience, never as security.
Conclusion
A good RBAC system is small and boring: a typed permission list, a role matrix, tenant-scoped memberships, a guard and a handful of ownership rules. Its value is that authorization stops being scattered conditionals and becomes a single, testable, auditable piece of the system. Build it early, keep it strict, and extend it by editing a table rather than rewriting code.
Frequently asked questions
+What is the difference between a role and a permission?
A permission is a specific allowed action, such as invoice:delete. A role is a named bundle of permissions, such as 'admin'. Code should check permissions; roles exist to assign permissions to people conveniently.
+Why check permissions instead of roles in code?
Checking roles hard-codes who may do what, so every new role means editing code. Checking permissions keeps code stable: you change which permissions a role has, not the guard clauses.
+Where should authorization be enforced?
On the server, at the point where the action happens (API handler and service layer). Hiding buttons in the UI improves usability but is not security, because clients can call your API directly.
+How do roles work in a multi-tenant app?
Roles belong to a membership: a user can be an admin in one tenant and a viewer in another. Always resolve the user's role for the current tenant, not a single global role.
+What about rules like 'users can edit their own posts'?
That is ownership or attribute-based access control. Combine RBAC with a resource check: the user needs the permission and must own the resource, or hold a broader permission such as post:edit_any.
+Should permissions be stored in the JWT?
Roles or a permissions version can be in the token for convenience, but tokens go stale when roles change. For sensitive operations, load the current role and permissions from the database or a short-lived cache.
+What is the safest default?
Deny by default. A request is forbidden unless a rule explicitly allows it, and unknown permissions or missing roles should fail closed.