주요 콘텐츠로 건너뛰기

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) — Like EnforceEx with 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.

관리 API

Get API

These methods return policy data. Example:

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)

GetAllSubjects() returns all subjects that appear in the policy (here: admin, alice, bob). Output:

[admin alice bob]

Use GetAllNamedSubjects("p") for a specific policy type. The same pattern applies for Objects, Actions, and Roles.

Other getters:

  • GetPolicy() / GetFilteredPolicy(0, "alice") — All rules or filtered by field.
  • GetNamedPolicy("p") / GetFilteredNamedPolicy("p", 0, "bob") — Same for a named policy.
  • GetGroupingPolicy() / GetFilteredGroupingPolicy(0, "alice") — Role-assignment rules.
  • GetNamedGroupingPolicy("g") / GetFilteredNamedGroupingPolicy("g", 0, "alice") — Same for named grouping.

Add, delete, update API

You can change policy at runtime. Example: add, remove, update, and check:

// 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

The same add/remove/update/has pattern exists for filtered and named policies and for grouping policies. For batch updates, use the plural forms (e.g. AddPolicies, UpdatePolicies) with slice arguments.

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

The AddEx methods add rules in batch but skip rules that already exist instead of failing:

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)

With AddPolicies, if one rule already exists the whole call fails and no rules are added. With AddPoliciesEx, existing rules are skipped and the rest are added. Example:

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

The enforcer also exposes RBAC helpers (roles, users, permissions). For the model setup, see RBAC.

Load model and policy as before:

enforcer, err := casbin.NewEnforcer("./example/model.conf", "./example/policy.csv")
if err != nil {
fmt.Printf("Error, details: %s\n", err)
}

Example RBAC calls:

roles, err := enforcer.GetRolesForUser("amber")
fmt.Println(roles) // [admin]
users, err := enforcer.GetUsersForRole("admin")
fmt.Println(users) // [amber abc]

GetRolesForUser("amber") returns [admin]. GetUsersForRole("admin") returns all users with that role. HasRoleForUser("amber", "admin") is true.

fmt.Println(enforcer.Enforce("bob", "data2", "write")) // true
enforcer.DeletePermission("data2", "write")
fmt.Println(enforcer.Enforce("bob", "data2", "write")) // false

DeletePermission("data2", "write") removes that permission for everyone. DeletePermissionForUser("alice", "data1", "read") removes it only for Alice.

For the full list of RBAC APIs, see RBAC API.