RBAC with Domains
การกำหนดบทบาทโดยมีโดเมนผู้เช่า
In Casbin, RBAC roles can be either global or domain-specific. Domain-specific roles allow a user to hold different roles across different domains or tenants. This capability is particularly valuable in large-scale systems such as cloud platforms, where users frequently operate within multiple distinct tenants.
The role definition for domains or tenants should be structured as follows:
[role_definition]
g = _, _, _
The third underscore _ denotes the domain or tenant name and must remain unchanged. With this setup, policies can be written like this:
p, admin, tenant1, data1, read
p, admin, tenant2, data2, read
g, alice, admin, tenant1
g, alice, user, tenant2
This configuration means that the admin role in tenant1 has read access to data1. Alice holds the admin role in tenant1 and the user role in tenant2, so she can read data1. However, because Alice is not an admin in tenant2, she cannot read data2.
In your matcher, verify the role as follows:
[matchers]
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act
Flexible Domain Token Naming
While the convention uses dom as the domain token name, Casbin supports arbitrary names for domain parameters. You can rename the domain token to better match your application's terminology, such as tenant, workspace, or any other meaningful identifier:
[request_definition]
r = sub, tenant, obj, act
[policy_definition]
p = sub, tenant, obj, act
[role_definition]
g = _, _, _
[matchers]
m = g(r.sub, p.sub, r.tenant) && r.tenant == p.tenant && r.obj == p.obj && r.act == p.act
When using pattern matching functions like keyMatch for domain matching, Casbin automatically detects your custom domain token name from the model definition, provided the domain is the second parameter (index 1) in both request and policy definitions:
[matchers]
m = g(r.sub, p.sub, r.tenant) && keyMatch(r.tenant, p.tenant) && r.obj == p.obj && r.act == p.act
This automatic detection eliminates the need for hardcoded token names in pattern matching scenarios. For using custom domain token names with domain-related APIs (like GetAllUsersByDomain()), refer to the Token Name Convention section below.
For additional examples, refer to rbac_with_domains_model.conf.
By convention, the domain token in policy definitions is named dom and is typically positioned as the second token (e.g., sub, dom, obj, act). Golang Casbin now supports custom token names and positions. If the domain token is named dom, it can be placed anywhere without extra configuration. For other names, call e.SetFieldIndex() with constant.DomainIndex after initializing the enforcer, regardless of token position.
# Using `domain` instead of `dom`
[policy_definition]
p = sub, obj, act, domain
e.SetFieldIndex("p", constant.DomainIndex, 3) // index starts from 0
users := e.GetAllUsersByDomain("domain1") // without SetFieldIndex, this will raise an error