Casbin之ABAC
1.model.conf文件
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[matchers]
m = r.sub.Hour >= 9 && r.sub.Hour < 18 || r.sub.Name == r.obj.Owner
[policy_effect]
e = some(where (p.eft == allow))
2.Policy.conf文件
注意:虽然不需要Policy.conf文件,但是还是得在model.conf定义
[policy_definition]
p = sub, obj, act与
[policy_effect]
e = some(where (p.eft == allow))
这两个都不能少
![image-20220216180922569](https://i-blog.csdnimg.cn/blog_migrate/39c6e5ab6670aa0038e93c6a6c7e2e30.png)
3.main
package main
import (
"fmt"
"github.com/casbin/casbin/v2"
"log"
)
type Object struct {
Name string
Owner string
}
type Subject struct {
Name string
Hour int
}
func check(e *casbin.Enforcer, sub Subject, obj Object, act string) {
ok, _ := e.Enforce(sub, obj, act)
if ok {
fmt.Printf("%s CAN %s %s at %d:00\n", sub.Name, act, obj.Name, sub.Hour)
} else {
fmt.Printf("%s CANNOT %s %s at %d:00\n", sub.Name, act, obj.Name, sub.Hour)
}
}
func main() {
e, err := casbin.NewEnforcer("./casbin/model.conf")
if err != nil {
log.Fatalf("NewEnforecer failed:%v\n", err)
}
o := Object{"data", "dajun"}
s1 := Subject{"dajun", 10}
check(e, s1, o, "read")
s2 := Subject{"lizi", 10}
check(e, s2, o, "read")
s3 := Subject{"dajun", 20}
check(e, s3, o, "read")
s4 := Subject{"lizi", 20}
check(e, s4, o, "read")
}
4.输出及结构
![image-20220216181411004](https://i-blog.csdnimg.cn/blog_migrate/da9682e5b61884165d4da12307ca974c.png)
![image-20220216181402855](https://i-blog.csdnimg.cn/blog_migrate/d77a2ce3cf2235e3d10725c037b26adc.png)
![image-20220216181521665](https://i-blog.csdnimg.cn/blog_migrate/585c6d64398f377c0a8d8dd72c3f82a0.png)
![image-20220216185010955](https://i-blog.csdnimg.cn/blog_migrate/8fbd4c1140526e571367632e6b208aa2.png)
5.讲解
![image-20220216180749733](https://i-blog.csdnimg.cn/blog_migrate/da29fb000497c3d6f20ca4e91179a86b.png)