跳转到主要内容

模型存储

Casbin 中的模型是 只读式加载 的:它们定义你的访问控制逻辑,在运行时被视为静态内容。没有任何 API 可以把模型保存或更新到存储中。

你可以通过三种方式加载模型:

从 CONF 文件加载​

从 .conf 文件加载是通常的做法,也便于共享和讨论模型。

示例:examples/rbac_model.conf

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act

在创建 enforcer 时使用它:

e := casbin.NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")

从代码加载​

你也可以不用文件,直接在代码中构建模型:

import (
"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v3/model"
"github.com/casbin/casbin/v3/persist/file-adapter"
)

// Build the model in Go.
m := model.NewModel()
m.AddDef("r", "r", "sub, obj, act")
m.AddDef("p", "p", "sub, obj, act")
m.AddDef("g", "g", "_, _")
m.AddDef("e", "e", "some(where (p.eft == allow))")
m.AddDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act")

// Load the policy rules from the .CSV file adapter.
// Replace it with your adapter to avoid using files.
a := fileadapter.NewAdapter("examples/rbac_policy.csv")

// Create the enforcer.
e := casbin.NewEnforcer(m, a)

从字符串加载​

你也可以从字符串加载模型(例如来自配置或数据库):

import (
"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v3/model"
)

// Model text (e.g. from config).
text :=
`
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
`
m, _ := model.NewModelFromString(text)

// Load the policy rules from the .CSV file adapter.
// Replace it with your adapter to avoid using files.
a := fileadapter.NewAdapter("examples/rbac_policy.csv")

// Create the enforcer.
e := casbin.NewEnforcer(m, a)