API Overview
This page gives an overview of Casbin’s main APIs. For setup and concepts, see Get started and How it works.
Enforce API
The examples below use an RBAC model in model.conf and policies in policy.csv. Model syntax is described in Model syntax. Example files:
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
Example usage:
// 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")
NewEnforcer() loads the model and policy from the given paths (or from a model and adapter). It returns an enforcer and an error. The default file adapter is used when you pass two file paths; you can substitute any adapter.
enforcer.Enforce("alice", "data1", "read") checks whether Alice can read data1. It returns (true, nil) when allowed and (false, nil) when denied. With the policy above, this call returns true.
EnforceEx API
To see which policy allowed a request, use EnforceEx():
ok, reason, err := enforcer.EnforceEx("amber", "data1", "read")
fmt.Println(ok, reason) // true [admin data1 read]
reason is the matching policy (e.g. [admin data1 read]). Amber has the admin role, so the policy p, admin, data1, read allows the request.
Related APIs:
-
ok, err := enforcer.EnforceWithMatcher(matcher, request)Enforce with a one-off matcher expression.
-
EnforceExWithMatcher(matcher, request)— LikeEnforceExwith a custom matcher. -
BatchEnforce(requests)— Enforce many requests at once; returns a slice of booleans.
See Management API and RBAC API for the full set.