Skip to content

Instantly share code, notes, and snippets.

@anhtuank7c
Last active September 20, 2024 18:22
Show Gist options
  • Save anhtuank7c/56ce024c060fb5d34cbb921f5ddd4da3 to your computer and use it in GitHub Desktop.
Save anhtuank7c/56ce024c060fb5d34cbb921f5ddd4da3 to your computer and use it in GitHub Desktop.
Casbin RBAC with resource roles example
# model.conf
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _ # Role inheritance between users and roles
g2 = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = (g(r.sub, p.sub) || g2(r.sub, p.sub)) && keyMatch(r.obj, p.obj) && r.act == p.act
# 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
p, social-department, /admin/posts, get
p, social-department, /admin/posts/add, post
p, social-department, /admin/posts/:id/edit, put
p, social-department, /admin/posts/:id/view, get
p, social-department, /admin/posts/:id/delete, delete
# matching pattern can be found at: https://casbin.org/docs/rbac-with-pattern/#use-pattern-matching-in-rbac
p, marketing-department, /admin/posts, get
p, marketing-department, /admin/posts/:id/view, get
g, user01, admin
g, user02, editor
g2, user01, social-department
g2, user02, marketing-department
g2, user03, marketing-department
# test
user01, /admin, get
user01, /admin/posts, get
user01, /admin/posts/add, post
user02, /admin/posts/add, post
user03, /admin/posts, get
user03, /admin/posts/add, post
# result
true Reason: ["admin","/admin","get"]
true Reason: ["admin","/admin/*","get"]
true Reason: ["admin","/admin/*","post"]
true Reason: ["editor","/admin/posts/add","post"]
true Reason: ["marketing-department","/admin/posts","get"]
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