Skip to main content


설치 으로

New a 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. When constructing this structure, model.conf and policy.csv will be loaded.

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 ""

e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
  • Use the Model text with other Adapter:
import (

xormadapter ""
_ ""

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

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

p = sub, obj, act

e = some(where (p.eft == allow))

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.

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