How to Set Up Multi‑Tenant RBAC in Casbin: Patterns, Config, and Sample Tests
This guide explains how Casbin supports global and domain‑specific RBAC roles, compares three multi‑tenant data isolation patterns, shows the configuration of a shared‑table approach with a domain‑aware model file, defines tenant policies and user groups, and provides PHP test code with expected outcomes.
Casbin allows RBAC roles to be defined globally or per specific domain (tenant). When a user belongs to different tenant groups, their effective role can change, which is essential for large cloud services where users are partitioned across multiple tenants.
Common Multi‑Tenant Isolation Patterns
1. Independent database : Each tenant has its own database, offering the highest isolation but at a higher development cost.
2. Shared database with separate schemas/tables : Tenants share a single database but maintain distinct schemas or tables.
3. Shared database and shared tables : All tenants use the same database and the same tables, distinguishing data by a TenantID column. This approach has the lowest cost and highest sharing, but the weakest isolation.
Configuration Example Using Pattern 3
The following example demonstrates the shared‑table approach.
User table illustration:
Tenant table illustration:
Model file rbac-domain-model.conf:
[request_definition]
r = sub, dom, obj, act
[policy_definition]
p = sub, dom, obj, act
[role_definition]
g = _, _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)Database Table Layout
Tenant Policy Definitions
Tenant doamin1 user admin can
GET /api/userTenant doamin2 user admin can
POST /api/userTenant User‑Group Assignments
User tinywan1 belongs to tenant doamin1 with role admin User tinywan2 belongs to tenant doamin2 with role
adminTest Code and Expected Results
PHP test snippets using the Casbin facade:
var_dump(Casbin::enforce('tinywan1', 'doamin1', '/api/user', 'GET')); // true
var_dump(Casbin::enforce('tinywan1', 'doamin2', '/api/user', 'POST')); // false
var_dump(Casbin::enforce('tinywan2', 'doamin1', '/api/user', 'GET')); // false
var_dump(Casbin::enforce('tinywan2', 'doamin2', '/api/user', 'POST')); // trueThe parameter order in enforce follows the model definition: r = sub, dom, obj, act.
Execution Result
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
