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.
管理API
取得API
These APIs retrieve specific policy elements. The example loads an enforcer and extracts information:
enforcer, err := casbin.NewEnforcer("./example/model.conf", "./example/policy.csv")
if err != nil {
fmt.Printf("Error, details: %s\n", err)
}
allSubjects := enforcer.GetAllSubjects()
fmt.Println(allSubjects)
The first four lines load information from local files, as shown previously.
The allSubjects := enforcer.GetAllSubjects() call retrieves all policy subjects as an array, which is then printed.
Expected output:
[admin alice bob]
Use GetAllNamedSubjects() to retrieve subjects from a specific named policy.
Replace Subject in the function name with Objects, Actions, or Roles to retrieve those elements instead.
Additional policy getters are available. Their usage patterns match those above.
policy = e.GetPolicy()retrieves all authorization rules.filteredPolicy := e.GetFilteredPolicy(0, "alice")retrieves authorization rules matching field filters.namedPolicy := e.GetNamedPolicy("p")retrieves all rules from a named policy.filteredNamedPolicy = e.GetFilteredNamedPolicy("p", 0, "bob")retrieves filtered rules from a named policy.groupingPolicy := e.GetGroupingPolicy()retrieves all role inheritance rules.filteredGroupingPolicy := e.GetFilteredGroupingPolicy(0, "alice")retrieves filtered role inheritance rules.namedGroupingPolicy := e.GetNamedGroupingPolicy("g")retrieves role inheritance rules from a named policy.namedGroupingPolicy := e.GetFilteredNamedGroupingPolicy("g", 0, "alice")retrieves filtered role inheritance rules from a named policy.
追加、削除、更新API
Casbin enables runtime policy modifications through various APIs.
This code demonstrates adding, removing, and updating policies, plus checking policy existence:
// load information from files
enforcer, err := casbin.NewEnforcer("./example/model.conf", "./example/policy.csv")
if err != nil {
fmt.Printf("Error, details: %s\n", err)
}
// add a policy and use HasPolicy() to confirm
enforcer.AddPolicy("added_user", "data1", "read")
hasPolicy := enforcer.HasPolicy("added_user", "data1", "read")
fmt.Println(hasPolicy) // true, the policy was added successfully
// remove a policy and use HasPolicy() to confirm
enforcer.RemovePolicy("alice", "data1", "read")
hasPolicy = enforcer.HasPolicy("alice", "data1", "read")
fmt.Println(hasPolicy) // false, the policy was removed successfully
// update a policy and use HasPolicy() to confirm
enforcer.UpdatePolicy([]string{"added_user", "data1", "read"}, []string{"added_user", "data1", "write"})
hasPolicy = enforcer.HasPolicy("added_user", "data1", "read")
fmt.Println(hasPolicy) // false, the original policy has expired
hasPolicy = enforcer.HasPolicy("added_user", "data1", "write")
fmt.Println(hasPolicy) // true, the new policy is in effect
These APIs enable dynamic policy editing. Similar APIs exist for FilteredPolicy, NamedPolicy, FilteredNamedPolicy, GroupingPolicy, NamedGroupingPolicy, FilteredGroupingPolicy, and FilteredNamedGroupingPolicy. Replace Policy in the function name with the desired category.
Batch operations use array parameters.
Example:
enforcer.UpdatePolicy([]string{"eve", "data3", "read"}, []string{"eve", "data3", "write"})
Change Policy to Policies and modify parameters for batch operations:
enforcer.UpdatePolicies([][]string{{"eve", "data3", "read"}, {"jack", "data3", "read"}}, [][]string{{"eve", "data3", "write"}, {"jack", "data3", "write"}})
Batch operations also apply to GroupingPolicy and NamedGroupingPolicy.
AddEx API
Casbin provides AddEx series APIs for batch rule addition with filtering.
AddPoliciesEx(rules [][]string) (bool, error)
AddNamedPoliciesEx(ptype string, rules [][]string) (bool, error)
AddGroupingPoliciesEx(rules [][]string) (bool, error)
AddNamedGroupingPoliciesEx(ptype string, rules [][]string) (bool, error)
SelfAddPoliciesEx(sec string, ptype string, rules [][]string) (bool, error)
These methods differ from their non-Ex counterparts by continuing to process remaining rules when encountering existing ones, rather than returning false immediately.
Compare AddPolicies and AddPoliciesEx with this test:
func TestDemo(t *testing.T) {
e, err := NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv")
if err != nil {
fmt.Printf("Error, details: %s\n", err)
}
e.ClearPolicy()
e.AddPolicy("user1", "data1", "read")
fmt.Println(e.GetPolicy())
testGetPolicy(t, e, [][]string{{"user1", "data1", "read"}})
// policy {"user1", "data1", "read"} now exists
// Use AddPolicies to add rules in batches
ok, _ := e.AddPolicies([][]string{{"user1", "data1", "read"}, {"user2", "data2", "read"}})
fmt.Println(e.GetPolicy())
// {"user2", "data2", "read"} failed to add because {"user1", "data1", "read"} already exists
// AddPolicies returns false and no other policies are checked, even though they may not exist in the existing ruleset
// ok == false
fmt.Println(ok)
testGetPolicy(t, e, [][]string{{"user1", "data1", "read"}})
// Use AddPoliciesEx to add rules in batches
ok, _ = e.AddPoliciesEx([][]string{{"user1", "data1", "read"}, {"user2", "data2", "read"}})
fmt.Println(e.GetPolicy())
// {"user2", "data2", "read"} is added successfully
// because AddPoliciesEx automatically filters the existing {"user1", "data1", "read"}
// ok == true
fmt.Println(ok)
testGetPolicy(t, e, [][]string{{"user1", "data1", "read"}, {"user2", "data2", "read"}})
}
RBAC API
Casbin provides APIs for modifying RBAC models and policies. For RBAC fundamentals, see here.
Load the model and policies as before:
enforcer, err := casbin.NewEnforcer("./example/model.conf", "./example/policy.csv")
if err != nil {
fmt.Printf("Error, details: %s\n", err)
}
Access RBAC APIs through the enforcer instance:
roles, err := enforcer.GetRolesForUser("amber")
fmt.Println(roles) // [admin]
users, err := enforcer.GetUsersForRole("admin")
fmt.Println(users) // [amber abc]
GetRolesForUser() returns all roles assigned to amber. Here, amber has only the admin role, yielding [admin]. GetUsersForRole() returns users belonging to a role, also as an array.
enforcer.HasRoleForUser("amber", "admin") // true
HasRoleForUser() confirms role membership. Since amber belongs to admin, this returns true.
fmt.Println(enforcer.Enforce("bob", "data2", "write")) // true
enforcer.DeletePermission("data2", "write")
fmt.Println(enforcer.Enforce("bob", "data2", "write")) // false
DeletePermission() removes a permission.
fmt.Println(enforcer.Enforce("alice", "data1", "read")) // true
enforcer.DeletePermissionForUser("alice", "data1", "read")
fmt.Println(enforcer.Enforce("alice", "data1", "read")) // false
DeletePermissionForUser() removes a specific user permission.
Additional RBAC APIs follow similar patterns. See next documents for complete details.