跳转至主要内容

API概述

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. 因此,当你开始阅读本教程时,我们假设你已经完全安装并将Casbin导入你的代码中。

用于强制执行的API(Enforce API)

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. 我们假设你能理解下面给出的配置文件。

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

阅读完配置文件后,请阅读以下代码:

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

这段代码从本地文件加载访问控制模型和策略。 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. 在这个例子中,ok的值是true

EnforceEx API

Sometimes you may wonder which policy allowed the request, so we have prepared the function EnforceEx(). 你可以像这样使用它:

ok, reason, err := enforcer.EnforceEx("amber", "data1", "read")
fmt.Println(ok, reason) // 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.

管理 API

Get API

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()
fmt.Println(allSubjects)

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

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.

AddEx API

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.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"}})
}

基于角色的访问控制接口

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. 您可以从这里获取详情。

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]
users, 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. 此函数的返回值也是一个数组。

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

您可以使用HasRoleForUser()来确认用户是否属于该角色。 在这个例子中,amber是管理员的成员,所以这个函数的返回值是true.

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

您可以使用 DeletePermission() 来删除权限。

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

然后使用 DeletePermissionForUser() 来删除用户的权限。

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.