Skip to content

Instantly share code, notes, and snippets.

@anhtuank7c
Last active September 20, 2024 18:22
Show Gist options
  • Save anhtuank7c/eeec11182ee2290b9de285b9456b624c to your computer and use it in GitHub Desktop.
Save anhtuank7c/eeec11182ee2290b9de285b9456b624c to your computer and use it in GitHub Desktop.
Casbin RBAC - Role Base Access Control
# model.conf
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _ # Role inheritance between users and roles
g2 = _,_ # Resource management between users and resources
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && r.act == p.act
# keyMatch to matching obj with wildcard
# policies.csv
p, admin, /admin, get
p, admin, /admin/*, get
p, admin, /admin/*, put
p, admin, /admin/*, post
p, admin, /admin/*, delete
p, admin, /admin/*, patch
p, editor, /admin, get
p, editor, /admin/posts, get
p, editor, /admin/posts/add, post
p, editor, /admin/posts/:id/edit, put
p, editor, /admin/posts/:id/view, get
p, editor, /admin/posts/:id/delete, delete
g, user01, admin
g, user02, editor
# test
user01, /admin, get
user01, /admin/posts, get
user01, /admin/posts/add, post
user01, /admin/users, get
user02, /admin, get
user02, /admin/posts, get
user02, /admin/posts/add, post
user02, /admin/posts/123/edit, put
user02, /admin/users, get
# result
true Reason: ["admin","/admin","get"]
true Reason: ["admin","/admin/*","get"]
true Reason: ["admin","/admin/*","post"]
true Reason: ["admin","/admin/*","get"]
true Reason: ["editor","/admin","get"]
true Reason: ["editor","/admin/posts","get"]
true Reason: ["editor","/admin/posts/add","post"]
false
false
@anhtuank7c
Copy link
Author

Casbin will automatically match /admin/posts/1/edit and /admin/posts/2/view into the pattern /admin/posts/:id/edit, /admin/posts/:id/view for you.

You only need to register the function with the enforcer like:

await e.addNamedMatchingFunc('g', Util.keyMatch2Func);

Read more: https://casbin.org/docs/rbac-with-pattern/#use-pattern-matching-in-rbac

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment