Zum Hauptinhalt springen


This overview only shows you how to use Casbin APIs and doesn't explain how Casbin is installed or how it works. You can find those tutorials here: Installation of Casbin and How Casbin Works. Wenn Sie also anfangen, dieses Tutorial zu lesen, gehen wir davon aus, dass Sie Casbin vollständig installiert und in Ihren Code importiert haben.

API erzwingen

Let's start with the Enforce APIs of Casbin. We will load a RBAC model from model.conf and load policies from policy.csv. You can learn about the Model syntax here, and we won't discuss it in this tutorial. Wir gehen davon aus, dass Sie die folgenden Konfigurationsdateien verstehen können:


r = sub, obj, act

p = sub, obj, act

g = _, _

e = some(where (p.eft == allow))

m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act


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

Nachdem Sie die Konfigurationsdateien gelesen haben, lesen Sie bitte den folgenden Code.

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

Dieser Code lädt das Zugriffskontrollmodell und die Richtlinien aus lokalen Dateien. The function casbin.NewEnforcer() will return an enforcer. It will recognize its two parameters as file paths and load the files from there. Errors occurred in the process are stored in the variable err. This code uses the default adapter to load the model and policies, and of course, you can achieve the same result by using a third-party adapter.

The code ok, err := enforcer.Enforce("alice", "data1", "read") is used to confirm access permissions. If Alice can access data1 with the read operation, the returned value of ok will be true; otherwise, it will be false. In diesem Beispiel ist der Wert von ok true.

EnforceEx API

Sometimes you may wonder which policy allowed the request, so we have prepared the function EnforceEx(). Sie können es so verwenden:

ok, reason, err := enforcer.EnforceEx("amber", "data1", "read")
fmt.Println(ok, Grund) // true [admin data1 read]

The EnforceEx() function will return the exact policy string in the return value reason. In this example, amber is an admin role, so the policy p, admin, data1, read allowed this request to be true. The output of this code is in the comment.

Casbin has provided many APIs similar to this one. These APIs add some extra functions to the basic ones. They include:

  • ok, err := enforcer.EnforceWithMatcher(matcher, request)

    This function uses a matcher.

  • ok, reason, err := enforcer.EnforceExWithMatcher(matcher, request)

    This is a combination of EnforceWithMatcher() and EnforceEx().

  • boolArray, err := enforcer.BatchEnforce(requests)

    This function allows for a list of jobs and returns an array.

This is a simple use case of Casbin. You can use Casbin to start an authorization server using these APIs. We will show you some other types of APIs in the following paragraphs.



These APIs are used to retrieve specific objects in policies. In this example, we are loading an enforcer and retrieving something from it.

Please take a look at the following code:

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

Similar to the previous example, the first four lines are used to load necessary information from local files. We won't discuss that here any further.

The code allSubjects := enforcer.GetAllSubjects() retrieves all the subjects in the policy file and returns them as an array. We then print that array.

Typically, the output of the code should be:

[admin alice bob]

You can also change the function GetAllSubjects() to GetAllNamedSubjects() to get the list of subjects that appear in the current named policy.

Similarly, we have prepared GetAll functions for Objects, Actions, Roles. To access these functions, you simply need to replace the word Subject in the function name with the desired category.

Additionally, there are more getters available for policies. The method of calling and the return values are similar to the ones mentioned above.

  • policy = e.GetPolicy() retrieves all the authorization rules in the policy.
  • filteredPolicy := e.GetFilteredPolicy(0, "alice") retrieves all the authorization rules in the policy with specified field filters.
  • namedPolicy := e.GetNamedPolicy("p") retrieves all the authorization rules in the named policy.
  • filteredNamedPolicy = e.GetFilteredNamedPolicy("p", 0, "bob") retrieves all the authorization rules in the named policy with specified field filters.
  • groupingPolicy := e.GetGroupingPolicy() retrieves all the role inheritance rules in the policy.
  • filteredGroupingPolicy := e.GetFilteredGroupingPolicy(0, "alice") retrieves all the role inheritance rules in the policy with specified field filters.
  • namedGroupingPolicy := e.GetNamedGroupingPolicy("g") retrieves all the role inheritance rules in the policy.
  • namedGroupingPolicy := e.GetFilteredNamedGroupingPolicy("g", 0, "alice") retrieves all the role inheritance rules in the policy with specified field filters.

API hinzufügen, löschen, Update API

Casbin provides a variety of APIs for dynamically adding, deleting, or modifying policies at runtime.

The following code demonstrates how to add, remove, and update policies, as well as how to check if a policy exists:

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

By using these APIs, you can edit your policies dynamically. Similarly, we have provided similar APIs for FilteredPolicy, NamedPolicy, FilteredNamedPolicy, GroupingPolicy, NamedGroupingPolicy, FilteredGroupingPolicy, FilteredNamedGroupingPolicy. To use them, simply replace the word Policy in the function name with the appropriate category.

Furthermore, by changing the parameters to arrays, you can perform batch editing of your policies.

For example, consider functions like this:

enforcer.UpdatePolicy([]string{"eve", "data3", "read"}, []string{"eve", "data3", "write"})

If we change Policy to Policies and modify the parameters as follows:

enforcer.UpdatePolicies([][]string{{"eve", "data3", "read"}, {"jack", "data3", "read"}}, [][]string{{"eve", "data3", "write"}, {"jack", "data3", "write"}})

then we can perform batch editing of these policies.

The same operations can also be applied to GroupingPolicy, NamedGroupingPolicy.


Casbin provides the AddEx series of APIs to help users add rules in batches.

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)

The difference between these methods and the methods without the Ex suffix is that if one of the rules already exists, they will continue checking the next rule instead of returning false immediately.

For example, let's compare AddPolicies and AddPoliciesEx.

You can run and observe the following code by copying it into the test under casbin.

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.AddPolicy("user1", "data1", "read")
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"}})
// {"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
testGetPolicy(t, e, [][]string{{"user1", "data1", "read"}})

// Use AddPoliciesEx to add rules in batches
ok, _ = e.AddPoliciesEx([][]string{{"user1", "data1", "read"}, {"user2", "data2", "read"}})
// {"user2", "data2", "read"} is added successfully
// because AddPoliciesEx automatically filters the existing {"user1", "data1", "read"}
// ok == true
testGetPolicy(t, e, [][]string{{"user1", "data1", "read"}, {"user2", "data2", "read"}})


Casbin provides some APIs for you to modify the RBAC model and policies. If you are familiar with RBAC, you can easily use these APIs.

Here, we only show you how to use the RBAC APIs of Casbin and won't talk about RBAC itself. Weitere Details erhalten Sie hier.

We use the following code to load the model and policies, just like before.

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

Then, we can use an instance of the Enforcer enforcer to access these APIs.

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

GetRolesForUser() returns an array that contains all the roles that amber has. In this example, amber has only one role, which is admin, so the array roles is [admin]. Similarly, you can use GetUsersForRole() to get the users who belong to a role. Der Rückgabewert dieser Funktion ist auch ein Array.

enforcer.HasRoleForUser("amber", "admin") // true

Sie können HasRoleForUser() verwenden, um zu bestätigen, ob der Benutzer zur Rolle gehört. In diesem Beispiel ist Bernstein Mitglied des Admins, also ist der Rückgabewert der Funktion true.

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

Sie können DeletePermission() verwenden, um eine Berechtigung zu löschen.

fmt.Println(enforcer.Enforce("alice", "data1", "read")) // true
enforcer.DeletePermissionForUser("alice", "data1", "read")
fmt.Println(enforcer.Enforce("alice", "data1", "read")) // false false

Und verwenden Sie DeletePermissionForUser() um eine Berechtigung für einen Benutzer zu löschen.

Casbin has many APIs like this. Their calling methods and return values have the same style as the above APIs. You can find these APIs in the next documents.