跳到主要内容

开始使用

Installation​

go get github.com/casbin/casbin/v3
从 v2 迁移到 v3

如果你要从 Casbin v2 升级到 v3,请将导入路径从 github.com/casbin/casbin/v2 更新为 github.com/casbin/casbin/v3。这也适用于所有子包(例如,v2/model 变为 v3/model)。

对于 Go modules,运行:

go get -u github.com/casbin/casbin/v3

然后更新代码中所有从 /v2 到 /v3 的导入。

Create a Casbin Enforcer​

Casbin 依赖配置文件来指定访问控制模型。

你需要两个配置文件:model.conf 和 policy.csv。Model 文件定义你的访问控制模型;Policy 文件保存权限规则。在实践中,你只需处理一个组件——Enforcer——它在创建时会加载这两个文件。

要创建一个 Enforcer,请提供一个 Model 和一个 Adapter。

Casbin 提供了一个你可以使用的 FileAdapter。有关更多信息,请参阅 Adapter。

  • 使用带有默认 FileAdapter 的 Model 文件的示例:
import "github.com/casbin/casbin/v3"

e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
  • 使用带有替代 Adapter 的 Model 文本的示例:
import (
"log"

"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v3/model"
xormadapter "github.com/casbin/xorm-adapter/v2"
_ "github.com/go-sql-driver/mysql"
)

// Initialize a Xorm adapter with MySQL database.
a, err := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/")
if err != nil {
log.Fatalf("error: adapter: %s", err)
}

m, err := model.NewModelFromString(`
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

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

[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
`)
if err != nil {
log.Fatalf("error: model: %s", err)
}

e, err := casbin.NewEnforcer(m, a)
if err != nil {
log.Fatalf("error: enforcer: %s", err)
}

Check Permissions​

在资源被访问之前,立即在你的代码中添加一个 enforcement check:

sub := "alice" // the user that wants to access a resource.
obj := "data1" // the resource that is going to be accessed.
act := "read" // the operation that the user performs on the resource.

ok, err := e.Enforce(sub, obj, act)

if err != nil {
// handle err
}

if ok == true {
// permit alice to read data1
} else {
// deny the request, show an error
}

// You could use BatchEnforce() to enforce some requests in batches.
// This method returns a bool slice, and this slice's index corresponds to the row index of the two-dimensional array.
// e.g. results[0] is the result of {"alice", "data1", "read"}
results, err := e.BatchEnforce([][]interface{}{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"jack", "data3", "read"}})

Casbin 提供了用于运行时权限管理的 API。例如,你可以检索分配给用户的所有角色:

roles, err := e.GetRolesForUser("alice")

有关更多示例,请参阅 Management API 和 RBAC API。你还可以浏览每种语言仓库中的测试用例。

Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.