RBAC with Domains
Role Definition with Domain Tenants
The RBAC roles in Casbin can be global or domain-specific. Domain-specific roles mean that the roles for a user can be different when the user is in different domains/tenants. This is very useful for large systems like a cloud, as users are usually in different tenants.
The role definition with domains/tenants should look like this:
[role_definition]
g = _, _, _
The third _
represents the name of the domain/tenant, and this part should not be changed. Then the policy can be:
p, admin, tenant1, data1, read
p, admin, tenant2, data2, read
g, alice, admin, tenant1
g, alice, user, tenant2
This means that the admin
role in tenant1
can read data1
. And alice
has the admin
role in tenant1
and the user
role in tenant2
. Therefore, she can read data1
. However, since alice
is not an admin
in tenant2
, she cannot read data2
.
Then, in a matcher, you should check 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
Please refer to the rbac_with_domains_model.conf for examples.
Note: Conventionally, the domain token name in policy definition is dom
and is placed as the second token (sub, dom, obj, act
).
Now, Golang Casbin supports customized token names and placement. If the domain token name is dom
, the domain token can be placed at an arbitrary position without any additional action. If the domain token name is not dom
, e.SetFieldIndex()
for constant.DomainIndex
should be called after the enforcer is initialized, regardless of its position.
# `domain` here for `dom`
[policy_definition]
p = sub, obj, act, domain
e.SetFieldIndex("p", constant.DomainIndex, 3) // index starts from 0
users := e.GetAllUsersByDomain("domain1") // without SetFieldIndex, it will raise an error