Installation


  1. go get github.com/casbin/casbin/v2

New a Casbin enforcer

The new a Casbin enforcer must provide a Model and a Adapter.
Casbin has a FileAdapter, see Adapter from more Adapter.


  1. import "github.com/casbin/casbin/v2"
  2. e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")

注意:上面提到的适配器adapter指的是 policy。

  • Use the Model text with other Adapter:

  1. import (
  2. "log"
  3. "github.com/casbin/casbin/v2"
  4. "github.com/casbin/casbin/v2/model"
  5. xormadapter "github.com/casbin/xorm-adapter/v2"
  6. _ "github.com/go-sql-driver/mysql"
  7. )
  8. // Initialize a Xorm adapter with MySQL database.
  9. a, err := xormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/casbin")
  10. if err != nil {
  11. log.Fatalf("error: adapter: %s", err)
  12. }
  13. m, err := model.NewModelFromString(`
  14. [request_definition]
  15. r = sub, obj, act
  16. [policy_definition]
  17. p = sub, obj, act
  18. [policy_effect]
  19. e = some(where (p.eft == allow))
  20. [matchers]
  21. m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
  22. `)
  23. if err != nil {
  24. log.Fatalf("error: model: %s", err)
  25. }
  26. e, err := casbin.NewEnforcer(m, a)
  27. if err != nil {
  28. log.Fatalf("error: enforcer: %s", err)
  29. }

Check permissions

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


  1. sub := "alice" // the user that wants to access a resource.
  2. obj := "data1" // the resource that is going to be accessed.
  3. act := "read" // the operation that the user performs on the resource.
  4. ok, err := e.Enforce(sub, obj, act)
  5. if err != nil {
  6. // handle err
  7. }
  8. if ok == true {
  9. // permit alice to read data1
  10. } else {
  11. // deny the request, show an error
  12. }

Casbin also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:


  1. roles := e.GetRolesForUser("alice")

See Management API and RBAC API for more usage.
Please refer to the test cases for more usage.