Moonlit Torii

Casbin Access Control

Casbin authorization: models, policies, roles, and Go integration.

01 Access Control Casbin

Casbin is a powerful and efficient open-source access control framework. Its permission management mechanism supports multiple access control models, and all programming languages have support for Casbin.

Currently, all my projects are based on simple role management.

Divided into three categories: accessible to non-logged-in users, accessible to regular users, and accessible to administrators.

When developing the RBAC system later, it will combine roles and access control, and Casbin can better help me accomplish this.

There are actually quite a lot of online documents about Casbin, but many of their examples are not very suitable, and it's easy for beginners to get confused the first time they look at them.

This document explains based on access control in actual web applications.

Basic Usage

Download

Go
go get github.com/casbin/casbin/v2

Casbin is composed of two parts: one is the configuration file, and the other is the set of rules.

For the first time learning, first get the demo running, don’t worry about understanding what these two things are yet.

Prepare two files, model.pml and policy.csv

model.pml

Go
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

[policy_effect]
e = some(where (p.eft == allow))

policy.csv

Go
p, zhangsan, /index, GET
p, zhangsan, /home, GET
p, zhangsan, /users, GET
p, zhangsan, /users, POST
p, wangwu, /index, GET
p, wangwu, /home, GET

demo.go

Go
package main

import (
  "fmt"
  "github.com/casbin/casbin/v2"
  "log"
)

func check(e *casbin.Enforcer, sub, obj, act string) {
  ok, _ := e.Enforce(sub, obj, act)
  if ok {
    fmt.Printf("%s CAN %s %s\n", sub, act, obj)
  } else {
    fmt.Printf("%s CANNOT %s %s\n", sub, act, obj)
  }
}

func main() {
  e, err := casbin.NewEnforcer("./model.pml", "./policy.csv")
  if err != nil {
    log.Fatalf("NewEnforecer failed:%v\n", err)
  }

  check(e, "zhangsan", "/index", "GET")
  check(e, "zhangsan", "/home", "GET")
  check(e, "zhangsan", "/users", "POST")
  check(e, "wangwu", "/users", "POST")
}

Under normal circumstances, you will get

Go
zhangsan CAN GET /index
zhangsan CAN GET /home
zhangsan CAN POST /users
wangwu CANNOT POST /users

Casbin Configuration File

At first, when I saw the model.pml and policy.csv files, I was probably completely confused.

Then let's take a look at Casbin's configuration file

Request

Representing a request. Look at our example above:

text
[request_definition]
r = sub, obj, act

A request is represented by three standard elements: the request subject, the request object, and the request operation.

Taking user fengfeng making a GET request to the /api/users endpoint as an example:

The requestor is fengfeng

The request target is /api/users

The requested operation is GET

Policy and Policy_Rule

Policy represents a strategy, it indicates what the rules for specific permission definitions are

The policies defined in the policy.csv file are policy_rule. They correspond one-to-one with Policy.

For example, our example above:

text
[policy_definition]
p = sub, obj, act

We have defined the rules of the policy as such, so each policy_rule we define in policy.csv must correspond one-to-one with this attribute.

Matcher

There are requests and there are rules. Whether a request matches a certain rule is determined by the matcher, for example:

YAML
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

indicates when

YAML
r.sub == p.sub && r.obj == p.obj && r.act == p.act

Returns true when it matches, otherwise returns false, that is, returns true when all three match exactly.

Effect

Effect is used to determine whether a request needs to be allowed if it meets the rules. Its rules are somewhat more complex.

For example, here we:

YAML
[policy_effect]
e = some(where (p.eft == allow))

Here, 'some' means that the number of expressions in the parentheses is greater than or equal to 1. What we mean in this sentence is that after comparing the request with all the policies, if the number of policy results (p.eft) that are 'allow' is greater than or equal to 1, then the overall policy for the request is true.

Access Control Model

In addition to what is mentioned in the documentation, Casbin also supports various access control models.

https://casbin.org/zh/docs/supported-models/

ACL Access Control

ACL is the earliest and also the most basic access control mechanism, and its principle is very simple:

Each resource is accompanied by a list, which records which users can perform which CRUD operations on that resource. When the system tries to access this resource, it first checks this list for the access permissions of the current user, thereby determining whether the current user can perform the corresponding operation. Overall, ACL is a resource-oriented access control model, and its mechanism revolves around the resource.

The demo above is an example of ACL access control.

Add rule

Go
e.AddPolicy("wangwu", "/users", "POST")
e.SavePolicy()

Delete rule

Go
e.RemovePolicy("wangwu", "/users", "POST")
e.SavePolicy()

RBAC Access Control

The ACL model is not a problem when there are relatively few users and resources, but when the number of users and resources increases, ACL becomes extremely cumbersome.

Imagine how painful it would be to have to reset the permissions for every new user each time.

The RBAC (role-based access control) model addresses this problem by introducing the role as an intermediate layer.

Each user belongs to a role, such as developer, administrator, or operations, and each role has its specific permissions. The addition and removal of permissions are handled through the role.

When we add a new user this way, we only need to assign them a role, and they will have all the permissions of that role.

When modifying a role's permissions, the permissions of the users belonging to this role will be correspondingly modified.

mode.pml file

Go
[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

Go
p, admin, /index, GET
p, admin, /home, GET
p, admin, /users, GET
p, admin, /users, POST
p, yunwei, /index, GET
p, yunwei, /home, GET
g, zhangsan, admin
g, wangwu, yunwei

The code for judgment is still the same

Go
check(e, "zhangsan", "/index", "GET")
check(e, "zhangsan", "/home", "GET")
check(e, "zhangsan", "/users", "POST")
check(e, "wangwu", "/users", "POST")

But once there is a role, when the system adds a new user, it only needs to assign this role to the user.

Then you can add a new role in role management, and then set the role's access permissions, specifying which interfaces it can access.

In this mode, a user can have multiple roles, for example

Go
p, admin, /index, GET
p, admin, /home, GET
p, admin, /users, GET
p, admin, /users, POST
p, yunwei, /index, GET
p, yunwei, /home, GET
g, zhangsan, admin
g, wangwu, yunwei
g, wangwu, admin

Add character

Go
e.AddPolicy("kuaiji", "/users", "GET")
e.SavePolicy()

Add user-role mapping

Go
e.AddRoleForUser("zhangsan", "kuaiji")
e.SavePolicy()

Delete user-role mapping

Go
e.RemoveGroupingPolicy("zhangsan", "kuaiji")
e.SavePolicy()

Delete Character

Go
e.RemovePolicy("kuaiji", "/users", "GET")
e.SavePolicy()

Integrating Casbin with Gorm

Actually, based on the above RBAC, a role-based access control feature can be implemented.

But currently the entire set of rules is stored in a file.

In actual applications, Casbin's rule set will definitely be stored in the database.

Go
go get github.com/casbin/gorm-adapter/v3

init gorm

Go
package core

import (
  "fmt"
  "github.com/sirupsen/logrus"
  "gorm.io/driver/mysql"
  "gorm.io/gorm"
  "gorm.io/gorm/logger"
  "time"
)

func InitGorm() *gorm.DB {
  dsn := "root:root@tcp(127.0.0.1:3306)/rule_db?charset=utf8mb4&parseTime=True&loc=Local"

  var mysqlLogger logger.Interface
  db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
    Logger:                                   mysqlLogger,
    DisableForeignKeyConstraintWhenMigrating: true,
  })
  if err != nil {
    logrus.Error(fmt.Sprintf("[%s] mysql连接失败", dsn))
    panic(err)
  }
  sqlDB, _ := db.DB()
  sqlDB.SetMaxIdleConns(10)               // 最大空闲连接数
  sqlDB.SetMaxOpenConns(100)              // 最多可容纳
  sqlDB.SetConnMaxLifetime(time.Hour * 4) // 连接最大复用时间,不能超过mysql的wait_timeout
  return db
}


When migrating the table, generate CasbinRule together.

Go
gormadapter "github.com/casbin/gorm-adapter/v3"

global.DB.AutoMigrate(
  &gormadapter.CasbinRule{},
)

casbin connects with gorm

Go
global.DB = core.InitGorm()
a, _ := gormadapter.NewAdapterByDB(global.DB)
m, err := model.NewModelFromFile("./testdata/model.pml")
if err != nil {
  logrus.Error("字符串加载模型失败!", err)
  return
}
e, _ := casbin.NewCachedEnforcer(m, a)
e.SetExpireTime(60 * 60)
_ = e.LoadPolicy()

CRUD operations of RBAC

Go
e.AddPolicy("admin", "/api/users", "GET")
e.AddRoleForUser("zhangsan", "admin")
check(e, "zhangsan", "/api/users", "GET")
e.RemoveGroupingPolicy("zhangsan", "admin")
e.RemovePolicy("admin", "/api/users", "GET")
check(e, "zhangsan", "/api/users", "GET")
e.SavePolicy()
check(e, "zhangsan", "/api/users", "GET")