**Model Storage**
Casbin 中的 Model 是仅加载(load-only)的:它们定义您的访问控制逻辑,并在运行时被视为静态数据。没有 API 用于在存储中保存或更新 Model。
您可以通过三种方式加载 Model:
从 CONF 文件加载
从 .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)
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.