跳转至主要内容

RBAC with Pattern

快速入门

  • Use pattern in g(_, _).

    e, _ := NewEnforcer("./example.conf", "./example.csv")
    e.AddNamedMatchingFunc("g", "KeyMatch2", util.KeyMatch2)
  • Use pattern with domain.

    e.AddNamedDomainMatchingFunc("g", "KeyMatch2", util.KeyMatch2)
  • Use all patterns.

    Just combine the use of both APIs.

As shown above, after you create the enforcer instance, you need to activate pattern matching via the AddNamedMatchingFunc and AddNamedDomainMatchingFunc APIs, which determine how the pattern matches.

备注

如果您使用在线编辑器,它会在左下角指定模式匹配函数。 编辑器提示

在 RBAC 中使用模式匹配

Sometimes, you want certain subjects, objects, or domains/tenants with a specific pattern to be automatically granted a role. RBAC中的模式匹配函数可以帮助做到这一点。 模式匹配函数与前一个函数共享相同的参数和返回值:matcher function

The pattern matching function supports each parameter of g.

We know that normally RBAC is expressed as g(r.sub, p.sub) in a matcher. Then we can use a policy like:

p, alice, book_group, read
g, /book/1, book_group
g, /book/2, book_group

因此alice 可以阅读所有书籍,包括book 1book 2。 But there can be thousands of books, and it's very tedious to add each book to the book role (or group) with one g policy rule.

不过,凭借着模式匹配函数,你可以把整个策略只用一行写下!

g, /book/:id, book_group

Casbin will automatically match /book/1 and /book/2 into the pattern /book/:id for you. 您需要做的仅仅是向enforcer注册该方法,例如像这样:

e.AddNamedMatchingFunc("g", "KeyMatch2", util.KeyMatch2)

When using a pattern matching function in domains/tenants, you need to register the function with the enforcer and model.

e.AddNamedDomainMatchingFunc("g", "KeyMatch2", util.KeyMatch2)

如果您不理解 g(r.sub, p.sub, r.dom) 意味着什么,请阅读 rbac-with-domins。 简而言之, g(r.sub, p.sub, r.dom) 将检查用户 r.sub 在域内 r.dom 是否具有角色 p.sub So this is how the matcher works. 您可以在这里查看完整的示例

除了上面的模式匹配语法外,我们还可以使用纯域模式。

For example, if we want sub to have access in different domains, domain1 and domain2, we can use the pure domain pattern:

p, admin, domain1, data1, read
p, admin, domain1, data1, write
p, admin, domain2, data2, read
p, admin, domain2, data2, write

g, alice, admin, *
g, bob, admin, domain2

In this example, we want alice to read and write data in domain1 and domain2. Pattern matching * in g makes alice have access to two domains.

By using pattern matching, especially in scenarios that are more complicated and have a lot of domains or objects to consider, we can implement the policy_definition in a more elegant and effective way.