Overview
This guide demonstrates Casbin API usage. For installation or architectural details, see Installation of Casbin and How Casbin Works. We assume you've completed installation and import before proceeding.
Enforce API
We'll load an RBAC model from model.conf and policies from policy.csv. Model syntax is explained here. Review the configuration files below:
model.conf
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
policy.csv
p, admin, data1, read
p, admin, data1, write
p, admin, data2, read
p, admin, data2, write
p, alice, data1, read
p, bob, data2, write
g, amber, admin
g, abc, admin
Review this code after examining the configuration files:
// Load information from files.
enforcer, err := casbin.NewEnforcer("./example/model.conf", "./example/policy.csv")
if err != nil {
log.Fatalf("Error, detail: %s", err)
}
ok, err := enforcer.Enforce("alice", "data1", "read")
This loads the access control model and policies from local files. The casbin.NewEnforcer() function returns an enforcer, interpreting its parameters as file paths. Any errors are captured in err. By default, this uses the built-in adapter, though third-party adapters work identically.
The ok, err := enforcer.Enforce("alice", "data1", "read") call checks access permissions. When Alice has permission to read data1, ok returns true; otherwise false. Here, the result is true.
EnforceEx API
To identify which policy permitted a request, use EnforceEx():
ok, reason, err := enforcer.EnforceEx("amber", "data1", "read")
fmt.Println(ok, reason) // true [admin data1 read]
EnforceEx() returns the matching policy string in reason. Since amber holds the admin role, the policy p, admin, data1, read authorizes this request. Output appears in the comment.
Casbin offers several similar enhanced APIs:
-
ok, err := enforcer.EnforceWithMatcher(matcher, request)Uses a custom matcher.
-
ok, reason, err := enforcer.EnforceExWithMatcher(matcher, request)Combines
EnforceWithMatcher()andEnforceEx(). -
boolArray, err := enforcer.BatchEnforce(requests)Processes multiple requests, returning an array of results.
These APIs provide the foundation for building an authorization server. Additional API categories follow.