casbin实现基于角色的HTTP权限控制

casbin介绍

casbin是由北大的一位博士生主导开发的一个基于Go语言的权限控制库。支持 ACLRBACABAC 等常用的访问控制模型。

casbinGolang项目的强大而高效的开源访问控制库。 它支持基于各种访问控制模型实施授权。

casbin的核心是一套基于PERM metamodel(Policy, Effect, Request, Matchers)的DSLCasbin从用这种DSL定义的配置文件中读取访问控制模型,作为后续权限验证的基础

Casbin做了什么

  • 支持自定义请求的格式,默认的请求格式为{subject, object, action}
  • 具有访问控制模型model和策略policy两个核心概念。
  • 支持RBAC中的多层角色继承,不止主体可以有角色,资源也可以具有角色。
  • 支持超级用户,如rootAdministrator,超级用户可以不受授权策略的约束访问任意资源。
  • 支持多种内置的操作符,如keyMatch,方便对路径式的资源进行管理,如/foo/bar可以映射到/foo*

Casbin不做的事情

  • 身份认证authentication(即验证用户的用户名、密码),casbin只负责访问控制。应该有其他专门的组件负责身份认证,然后由casbin进行访问控制,二者是相互配合的关系。
  • 管理用户列表或角色列表。Casbin认为由项目自身来管理用户、角色列表更为合适,用户通常有他们的密码,但是Casbin的设计思想并不是把它作为一个存储密码的容器。而是存储RBAC方案中用户和角色之间的映射关系。

配置示例

模型与策略定制

  1. //sub "alice"// 想要访问资源的用户.
  2. //obj "data1" // 要访问的资源.
  3. //act "read" // 用户对资源执行的操作.
  4. # Request definition
  5. [request_definition]
  6. r = sub, obj, act
  7. # Policy definition
  8. [policy_definition]
  9. p = sub, obj, act
  10. # Policy effect
  11. [policy_effect]
  12. e = some(where (p.eft == allow))
  13. # Matchers
  14. [matchers]
  15. m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

可以看到这个配置文件主要定义了RequestPolicy的组成结构.Policy effectMatchers则灵活的多,可以包含一些自定义的表达式比如我们要加入一个名叫root的超级管理员,就可以这样写:

  1. [matchers]
  2. m = r.sub == p.sub && r.obj == p.obj && r.act == p.act || r.sub == "root"

又比如我们可以用正则匹配来判断权限是否匹配:

  1. [matchers]
  2. m = r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)

具体规则设置

  1. p, alice, data1, read
  2. p, bob, data2, write

意思就是 alice 可以读 data1,bob 可以写 data2

示例

模型与策略定制 test.conf

  1. [request_definition]
  2. r = sub, dom, obj, act
  3. [policy_definition]
  4. p = sub, dom, obj, act
  5. [role_definition]
  6. g = _, _, _
  7. [policy_effect]
  8. e = some(where (p.eft == allow))
  9. [matchers]
  10. m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act

具体规则设置 test.csv

  1. p, admin, domain1, data1, read
  2. p, admin, domain1, data1, write
  3. p, admin, domain2, data2, read
  4. p, admin, domain2, data2, write
  5. g, alice, admin, domain1
  6. g, bob, admin, domain2

如上所示,alice 和 bob 分别是 domian1 和 domain2 的管理员

iris示例代码

1.中间件格式 错误返回forbidden

目录结构

主目录middleware

  1. —— casbinmodel.conf
  2. —— casbinpolicy.csv
  3. —— main.go
  4. —— main_test.go

代码示例

casbinmodel.conf

  1. [request_definition]
  2. r = sub, obj, act
  3. [policy_definition]
  4. p = sub, obj, act
  5. [role_definition]
  6. g = _, _
  7. [policy_effect]
  8. e = some(where (p.eft == allow))
  9. [matchers]
  10. m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")

casbinpolicy.csv

  1. p, alice, /dataset1/*, GET
  2. p, alice, /dataset1/resource1, POST
  3. p, bob, /dataset2/resource1, *
  4. p, bob, /dataset2/resource2, GET
  5. p, bob, /dataset2/folder1/*, POST

main.go

  1. package main
  2. import (
  3. "github.com/kataras/iris"
  4. "github.com/casbin/casbin"
  5. cm "github.com/iris-contrib/middleware/casbin"
  6. )
  7. // $ go get github.com/casbin/casbin
  8. // $ go run main.go
  9. // Enforcer映射模型和casbin服务的策略,我们也在main_test上使用此变量。
  10. var Enforcer = casbin.NewEnforcer("casbinmodel.conf", "casbinpolicy.csv")
  11. func newApp() *iris.Application {
  12. casbinMiddleware := cm.New(Enforcer)
  13. app := iris.New()
  14. app.Use(casbinMiddleware.ServeHTTP)
  15. app.Get("/", hi)
  16. app.Get("/dataset1/{p:path}", hi) // p, alice, /dataset1/*, GET
  17. app.Post("/dataset1/resource1", hi)
  18. app.Get("/dataset2/resource2", hi)
  19. app.Post("/dataset2/folder1/{p:path}", hi)
  20. app.Any("/dataset2/resource1", hi)
  21. return app
  22. }
  23. func main() {
  24. app := newApp()
  25. app.Run(iris.Addr(":8080"))
  26. }
  27. func hi(ctx iris.Context) {
  28. ctx.Writef("Hello %s", cm.Username(ctx.Request()))
  29. }

main_test.go

  1. package main
  2. import (
  3. "testing"
  4. "github.com/iris-contrib/httpexpect"
  5. "github.com/kataras/iris/httptest"
  6. )
  7. func TestCasbinMiddleware(t *testing.T) {
  8. app := newApp()
  9. e := httptest.New(t, app, httptest.Debug(false))
  10. type ttcasbin struct {
  11. username string
  12. path string
  13. method string
  14. status int
  15. }
  16. tt := []ttcasbin{
  17. {"alice", "/dataset1/resource1", "GET", 200},
  18. {"alice", "/dataset1/resource1", "POST", 200},
  19. {"alice", "/dataset1/resource2", "GET", 200},
  20. {"alice", "/dataset1/resource2", "POST", 404},
  21. {"bob", "/dataset2/resource1", "GET", 200},
  22. {"bob", "/dataset2/resource1", "POST", 200},
  23. {"bob", "/dataset2/resource1", "DELETE", 200},
  24. {"bob", "/dataset2/resource2", "GET", 200},
  25. {"bob", "/dataset2/resource2", "POST", 404},
  26. {"bob", "/dataset2/resource2", "DELETE", 404},
  27. {"bob", "/dataset2/folder1/item1", "GET", 404},
  28. {"bob", "/dataset2/folder1/item1", "POST", 200},
  29. {"bob", "/dataset2/folder1/item1", "DELETE", 404},
  30. {"bob", "/dataset2/folder1/item2", "GET", 404},
  31. {"bob", "/dataset2/folder1/item2", "POST", 200},
  32. {"bob", "/dataset2/folder1/item2", "DELETE", 404},
  33. }
  34. for _, tt := range tt {
  35. check(e, tt.method, tt.path, tt.username, tt.status)
  36. }
  37. }
  38. func check(e *httpexpect.Expect, method, path, username string, status int) {
  39. e.Request(method, path).WithBasicAuth(username, "password").Expect().Status(status)
  40. }

2.路由修饰模式 错误返回403

目录结构

主目录wrapper

  1. —— casbinmodel.conf
  2. —— casbinpolicy.csv
  3. —— main.go
  4. —— main_test.go

代码示例

casbinmodel.conf

  1. [request_definition]
  2. r = sub, obj, act
  3. [policy_definition]
  4. p = sub, obj, act
  5. [role_definition]
  6. g = _, _
  7. [policy_effect]
  8. e = some(where (p.eft == allow))
  9. [matchers]
  10. m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")

casbinpolicy.csv

  1. p, alice, /dataset1/*, GET
  2. p, alice, /dataset1/resource1, POST
  3. p, bob, /dataset2/resource1, *
  4. p, bob, /dataset2/resource2, GET
  5. p, bob, /dataset2/folder1/*, POST
  6. p, cathrin, /dataset2/resource2, GET
  7. p, dataset1_admin, /dataset1/*, *
  8. g, cathrin, dataset1_admin

main.go

  1. package main
  2. import (
  3. "github.com/kataras/iris"
  4. "github.com/casbin/casbin"
  5. cm "github.com/iris-contrib/middleware/casbin"
  6. )
  7. // $ go get github.com/casbin/casbin
  8. // $ go run main.go
  9. // Enforcer映射模型和casbin服务的策略,我们也在main_test上使用此变量。
  10. var Enforcer = casbin.NewEnforcer("casbinmodel.conf", "casbinpolicy.csv")
  11. func newApp() *iris.Application {
  12. casbinMiddleware := cm.New(Enforcer)
  13. app := iris.New()
  14. app.WrapRouter(casbinMiddleware.Wrapper())
  15. app.Get("/", hi)
  16. app.Any("/dataset1/{p:path}", hi) // p, dataset1_admin, /dataset1/*, * && p, alice, /dataset1/*, GET
  17. app.Post("/dataset1/resource1", hi)
  18. app.Get("/dataset2/resource2", hi)
  19. app.Post("/dataset2/folder1/{p:path}", hi)
  20. app.Any("/dataset2/resource1", hi)
  21. return app
  22. }
  23. func main() {
  24. app := newApp()
  25. app.Run(iris.Addr(":8080"))
  26. }
  27. func hi(ctx iris.Context) {
  28. ctx.Writef("Hello %s", cm.Username(ctx.Request()))
  29. }

main_test.go

  1. package main
  2. import (
  3. "testing"
  4. "github.com/iris-contrib/httpexpect"
  5. "github.com/kataras/iris/httptest"
  6. )
  7. func TestCasbinWrapper(t *testing.T) {
  8. app := newApp()
  9. e := httptest.New(t, app)
  10. type ttcasbin struct {
  11. username string
  12. path string
  13. method string
  14. status int
  15. }
  16. tt := []ttcasbin{
  17. {"alice", "/dataset1/resource1", "GET", 200},
  18. {"alice", "/dataset1/resource1", "POST", 200},
  19. {"alice", "/dataset1/resource2", "GET", 200},
  20. {"alice", "/dataset1/resource2", "POST", 403},
  21. {"bob", "/dataset2/resource1", "GET", 200},
  22. {"bob", "/dataset2/resource1", "POST", 200},
  23. {"bob", "/dataset2/resource1", "DELETE", 200},
  24. {"bob", "/dataset2/resource2", "GET", 200},
  25. {"bob", "/dataset2/resource2", "POST", 403},
  26. {"bob", "/dataset2/resource2", "DELETE", 403},
  27. {"bob", "/dataset2/folder1/item1", "GET", 403},
  28. {"bob", "/dataset2/folder1/item1", "POST", 200},
  29. {"bob", "/dataset2/folder1/item1", "DELETE", 403},
  30. {"bob", "/dataset2/folder1/item2", "GET", 403},
  31. {"bob", "/dataset2/folder1/item2", "POST", 200},
  32. {"bob", "/dataset2/folder1/item2", "DELETE", 403},
  33. }
  34. for _, tt := range tt {
  35. check(e, tt.method, tt.path, tt.username, tt.status)
  36. }
  37. ttAdmin := []ttcasbin{
  38. {"cathrin", "/dataset1/item", "GET", 200},
  39. {"cathrin", "/dataset1/item", "POST", 200},
  40. {"cathrin", "/dataset1/item", "DELETE", 200},
  41. {"cathrin", "/dataset2/item", "GET", 403},
  42. {"cathrin", "/dataset2/item", "POST", 403},
  43. {"cathrin", "/dataset2/item", "DELETE", 403},
  44. }
  45. for _, tt := range ttAdmin {
  46. check(e, tt.method, tt.path, tt.username, tt.status)
  47. }
  48. Enforcer.DeleteRolesForUser("cathrin")
  49. ttAdminDeleted := []ttcasbin{
  50. {"cathrin", "/dataset1/item", "GET", 403},
  51. {"cathrin", "/dataset1/item", "POST", 403},
  52. {"cathrin", "/dataset1/item", "DELETE", 403},
  53. {"cathrin", "/dataset2/item", "GET", 403},
  54. {"cathrin", "/dataset2/item", "POST", 403},
  55. {"cathrin", "/dataset2/item", "DELETE", 403},
  56. }
  57. for _, tt := range ttAdminDeleted {
  58. check(e, tt.method, tt.path, tt.username, tt.status)
  59. }
  60. }
  61. func check(e *httpexpect.Expect, method, path, username string, status int) {
  62. e.Request(method, path).WithBasicAuth(username, "password").Expect().Status(status)
  63. }

提示

  • 以上的go iris都是使用Basic Auth,用postman测试请选择Authorization选项
  • .conf文件是配置规则模型,.csv是具体规则的体现,当然也可不使用这些东西,用户数据或者其他代替
  • 解释一下我对这些的理解
  1. //policy策略
  2. p, alice, /dataset1/*, GET //alice 用户有对 method为GET路径满足 /dataset1/*的访问权限 下面同理
  3. p, alice, /dataset1/resource1, POST
  4. p, bob, /dataset2/resource1, *
  5. p, bob, /dataset2/resource2, GET
  6. p, bob, /dataset2/folder1/*, POST
  7. p, cathrin, /dataset2/resource2, GET
  8. p, dataset1_admin, /dataset1/*, *
  9. g, cathrin, dataset1_admin //cathrin用户属于dataset1_admin组,也就是dataset1_admin能访问的cathrin都能访问,反之不然
  1. //配置
  2. [request_definition] //请求定义
  3. r = sub, obj, act
  4. [policy_definition] //策略定义,也就是*.cvs文件 p 定义的格式
  5. p = sub, obj, act
  6. [role_definition] //组定义,也就是*.cvs文件 g 定义的格式
  7. g = _, _
  8. [policy_effect]
  9. e = some(where (p.eft == allow))
  10. [matchers] //满足条件
  11. m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")
  12. //请求用户与满足*.cvs p(策略)且满足g(组规则)且请求资源满足p(策略)规定资源