跳转至主要内容

开始使用

安装

go get github.com/casbin/casbin/v2

新建一个Casbin enforcer

Casbin uses configuration files to define the access control model.

There are two configuration files: model.conf and policy.csv. model.conf stores the access model, while policy.csv stores the specific user permission configuration. The usage of Casbin is very straightforward. We only need to create one main structure: enforcer. 当构造这个结构的时候, model.confpolicy.csv 将会被加载。

In other words, to create a Casbin enforcer, you need to provide a Model and an Adapter.

Casbin provides a FileAdapter that you can use. See Adapter for more information.

  • Example of using the Model file and the default FileAdapter:
import "github.com/casbin/casbin/v2"

e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
  • 与其他Adapter一起使用Model text
import (
"log"

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

// 使用MySQL数据库初始化一个Xorm适配器
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)
}

检查权限

在访问发生之前, 在代码中添加强制挂钩:

sub := "alice" // 想要访问资源的用户。
obj := "data1" // 将被访问的资源。
act := "read" // 用户对资源执行的操作。

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

if err != nil {
// 处理err
}

if ok == true {
// 允许alice读取data1
} else {
// 拒绝请求,抛出异常
}

// 您可以使用BatchEnforce()来批量执行一些请求
// 这个方法返回布尔切片,此切片的索引对应于二维数组的行索引。
// 例如results[0] 是{"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 APIRBAC API

请查看测试用例以获取更多使用方式。