Skip to main content

Get Started


go get

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 for more information.

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

Add an enforcement hook into your code right before the access happens:

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

Please refer to the test cases for more usage.