Casbin之支持资源角色的RBAC
1.model.conf文件
[request_definition]
r = sub,obj,act
[policy_definition]
p = sub,obj,act
[policy_effect]
e = some(where (p.eft == allow))
[role_definition]
g=_,_
g2=_,_
[matchers]
m = g(r.sub, p.sub) && g2(r.obj, p.obj) && r.act == p.act
![image-20220216171638112](https://i-blog.csdnimg.cn/blog_migrate/dd5df497bb688d872341f879b24a4fcc.png)
2.Policy.csv文件
p, admin, prod, read
p, admin, prod, write
p, admin, dev, read
p, admin, dev, write
p, developer, dev, read
p, developer, dev, write
p, developer, prod, read
g, dajun, admin
g, lizi, developer
g2, prod.data, prod
g2, dev.data, dev
3.main
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("./casbin/model.conf", "./casbin/Policy.csv")
if err != nil {
log.Fatalf("NewEnforecer failed:%v\n", err)
}
check(e, "dajun", "prod.data", "read")
check(e, "dajun", "prod.data", "write")
check(e, "lizi", "dev.data", "read")
check(e, "lizi", "dev.data", "write")
check(e, "lizi", "prod.data", "write")
}
4.输出及结构
![image-20220216171849459](https://i-blog.csdnimg.cn/blog_migrate/26480079713e54878caaf500942da1ed.png)
![image-20220216171839792](https://i-blog.csdnimg.cn/blog_migrate/2f001bccb88e0d28df1e496751bfaf17.png)
5.讲解
![image-20220216171624341](https://i-blog.csdnimg.cn/blog_migrate/bbb83ab77754be14a7599cf21c4bd504.png)