Installation
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.
- Use the Model file and default FileAdapter:
import "github.com/casbin/casbin/v2"e, err := casbin.NewEnforcer("path/to/model.conf", "path/to/policy.csv")
注意:上面提到的适配器adapter指的是 policy。
- 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
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}
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 := e.GetRolesForUser("alice")
See Management API and RBAC API for more usage.
Please refer to the test cases for more usage.
