Golang RBAC 教程:Gin 中的基于角色的访问控制
本教程为使用 Gin 编写的 Go REST API 添加了基于角色的访问控制 (RBAC)。最终,三个角色 (admin, editor, viewer) 在不同的路由上被允许不同的 HTTP 方法,且规则位于策略文件中,您可以修改该文件而无需触及处理程序。
相同的模型和策略适用于所有 Casbin 实现,因此您可以在本教程的 Node.js、Python、Java 和 Rust 版本中重复使用它们。对于 gRPC 服务,请参阅 Go 中的 gRPC 授权。
1. 安装
go mod init example.com/rbac
go get github.com/casbin/casbin/v3 github.com/gin-gonic/gin
2. 编写模型
模型定义了请求的结构以及如何将其与策略进行匹配。将此保存为 model.conf:
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)
r = sub, obj, act:每个请求包含用户、URL 路径和 HTTP 方法。g = _, _:用户可以被分配给角色。g(r.sub, p.sub):请求的用户必须拥有策略规则中指定的角色。keyMatch2匹配诸如/api/articles/:id的路径,而regexMatch允许一条规则列出多个方法。有关其他内置匹配器,请参阅 Functions。
3. 编写策略
将此保存为 policy.csv:
p, admin, /api/*, (GET)|(POST)|(PUT)|(DELETE)
p, editor, /api/articles, (GET)|(POST)
p, editor, /api/articles/:id, (GET)|(PUT)
p, viewer, /api/articles, GET
p, viewer, /api/articles/:id, GET
g, alice, admin
g, bob, editor
g, carol, viewer
以 p 开头的行授予角色对路径和方法集的访问权限。以 g 开头的行将用户分配给角色。
4. 添加中间件
中间件调用 Enforce 并传入用户、路径和方法,如果 Casbin 判定拒绝,则以 403 Forbidden 拒绝请求。
main.go
package main
import (
"log"
"net/http"
"github.com/casbin/casbin/v3"
"github.com/gin-gonic/gin"
)
// Authorize asks Casbin whether the current user may call this route.
func Authorize(e *casbin.Enforcer) gin.HandlerFunc {
return func(c *gin.Context) {
// Replace this with the user from your session or JWT.
user := c.GetHeader("X-User")
allowed, err := e.Enforce(user, c.Request.URL.Path, c.Request.Method)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !allowed {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
return
}
c.Next()
}
}
func main() {
e, err := casbin.NewEnforcer("model.conf", "policy.csv")
if err != nil {
log.Fatal(err)
}
r := gin.Default()
api := r.Group("/api", Authorize(e))
api.GET("/articles", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"articles": []string{}}) })
api.POST("/articles", func(c *gin.Context) { c.JSON(http.StatusCreated, gin.H{"created": true}) })
api.PUT("/articles/:id", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"updated": c.Param("id")}) })
api.DELETE("/articles/:id", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"deleted": c.Param("id")}) })
log.Fatal(r.Run(":8080"))
}
备注
X-User 头仅用于简化示例。Casbin 只处理授权;在实际应用中,用户名来自您的身份验证层,例如经过验证的 JWT 或会话。
5. 试一试
go run .
curl -i -X POST -H "X-User: bob" http://localhost:8080/api/articles # 201, editors can create
curl -i -X DELETE -H "X-User: bob" http://localhost:8080/api/articles/1 # 403, editors cannot delete
curl -i -X DELETE -H "X-User: alice" http://localhost:8080/api/articles/1 # 200, admins can
curl -i -X POST -H "X-User: carol" http://localhost:8080/api/articles # 403, viewers are read-only
6. 在运行时更改角色
角色和权限是数据,因此您可以在服务器运行时更改它们:
e.AddRoleForUser("dave", "editor") // dave becomes an editor
e.DeleteRoleForUser("bob", "editor") // bob is no longer an editor
e.AddPolicy("editor", "/api/comments", "POST") // editors may now post comments
roles, _ := e.GetRolesForUser("alice") // [admin]
完整列表请参见 RBAC API 和 Management API。
下一步
- 将策略存储在数据库中。 使用 MySQL、PostgreSQL、MongoDB、Redis 等的 适配器 替换
policy.csv。随后通过 API 进行的策略更改将自动保存。 - 运行多个实例。 使用 监视器,以便当一个实例更改策略时,所有实例都能重新加载策略。
- 多租户应用程序。 带域名的 RBAC 使不同租 户中的用户拥有不同的角色。
- 基于属性的规则。 将角色与 ABAC 结合使用,例如“编辑只能更新自己的文章”。ABAC 教程 逐步构建此功能。
- 现成的中间件。 中间件列表 提供了针对 Gin、Echo、Fiber、Chi 和其他框架的插件。
- 在浏览器中实验。 将模型和策略粘贴到 在线编辑器 中,以在不运行任何代码的情况下测试请求。
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.