Skip to main content

시작하기

설치

github.com/casbin/casbin/v2 으로

New a Casbin enforcer

Casbin uses configuration files to set the access control model.

It has two configuration files, model.conf and policy.csv. Among them, model.conf stores our access model, and policy.csv stores our specific user permission configuration. The use of Casbin is very refined. Basically, we just need one main structure: enforcer. When constructing this structure, model.conf and policy.csv will be loaded.

In another word, to new a Casbin enforcer, you must provide a Model and an Adapter.

Casbin has a FileAdapter, see Adapter from more Adapter.

import "github.com/casbin/casbin/v2"

e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
  • Use the Model text with other Adapter:
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"
)

// Initialize a Xorm adapter with MySQL database.
a, err := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/casbin")
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

접근을 통제할 코드 부분에 검사 조건문을 추가하세요.

sub := "alice" // 보안 주체
obj := "data1" // 접근 대상 리소스
act := "read" // 보안 주체가 리소스에 대해 수행하려는 동작

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 also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:

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

See Management API and RBAC API for more usage.

더 많은 사용법을 알아보려면 테스트 케이스도 참조하세요.