RPEM权限模型

Model语法

Model CONF 至少应包含四个部分: [request_definition], [policy_definition], [policy_effect], [matchers]。如果 model 使用 RBAC, 还需要添加[role_definition]部分。Model CONF 文件可以包含注释。注释以 # 开头, # 会注释该行剩余部分。

下面是model.conf的文件案例:

// Request: 访问请求, 也就是谁想操作什么
[request_definition]
r = sub, obj, act

// policy_definition:定义权限的规则
[policy_definition]
p = sub, obj, act

// role_definition:用户 角色模型的定义
[role_definition]
g = _, _

// policy_effect: 定义组合了多个 Policy 之后的结果, allow/deny
[policy_effect]
e = some(where (p.eft == allow))

// Matcher: 判断 Request 是否满足 Policy
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act

下面是policy.cvs文件的内容:

p, superAdmin, project, read
p, superAdmin, project, write
p, admin, project, read
p, admin, project, write
p, admin, asse, read
p, admin, asse, write
p, zhuangjia, project, write
p, zhuangjia, asse, write
p, shangshang, project, read
p, shangshang, asse, read

g, quyuan, admin
g, wenyin, zhuangjia

匹配规则:

支持的内在政策效应是:

Policy effect意义示例
some(where (p.eft == allow))只要有一项匹配就成功ACL, RBAC, etc.
!some(where (p.eft == deny))只要有一项拒绝就失败Deny-override
some(where (p.eft == allow)) && !some(where (p.eft == deny))只要有一项匹配,并且没有任何拒绝Allow-and-deny
priority(p.eft) || deny Priority
subjectPriority(p.eft)基于角色的优先级主题优先级

案例

image-20220614161548742

数据库不需要配置自己新建表,只需要在适配器里面加上一个true 就行了,casbin会在第一次执行的时候检测是否拥有casbin相关的表,如果没有自动给我们创建数据库,表的相关字段是按照policy,sub,obj,act,eft,

a, err := xormadapter.NewAdapter("mysql", "ziop:ziop@tcp(127.0.0.1:3306)/ziop", true)

image-20220614161826730

image-20220614161911245

image-20220614172301572

package main

import (
	"github.com/casbin/casbin/v2"
	xormadapter "github.com/casbin/xorm-adapter/v2"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

func main() {

	a, err := xormadapter.NewAdapter("mysql", "ziop:ziop@tcp(127.0.0.1:3306)/ziop", true)
	if err != nil {
		log.Fatalf("error: adapter: %s", err)
	}
	//规则源 设置
	enforcer, err := casbin.NewEnforcer(".\model\model.conf", a)
	if err != nil {
		log.Fatalf("error: model: %s", err)
	}

	//测试
	sub := "ziop"  // the user that wants to access a resource.
	obj := "data"  // the resource that is going to be accessed.
	act := "write" // the operation that the user performs on the resource.

	// 新增规则
	//policy, err := enforcer.AddPolicy([]string{"ziop", "data", "write", "allow"})
	if err != nil {
		return
	}
	ok, err := enforcer.Enforce(sub, obj, act)
	//println(policy)

	if ok == true {
		// permit alice to read data1
		println("通过")
	} else {
		// deny the request, show an error
		println("拒绝")
	}

	//更新规则
	policy, err := enforcer.UpdatePolicy([]string{"ziop", "data", "write", "allow"}, []string{"ziop", "data", "read"})
	if err != nil {
		return
	}
	println(policy)

	ok, err = enforcer.Enforce(sub, obj, act)
	if ok == true {
		// permit alice to read data1
		println("通过")
	} else {
		// deny the request, show an error
		println("拒绝")
	}

}

image-20220614163244103

上一篇