Go 中的 ABAC
基于角色的访问控制回答的是“编辑人员可以做什么?”。许多实际规则需要的不仅仅是角色:作者可以编辑自己的草稿,编辑人员可以编辑自己部门的文章,任何人都可以阅读已发布的文章。这些规则依赖于用户和资源属性,这正是基于属性的访问控制 (ABAC) 的用途。
本教程 使用标准 net/http 包构建一个小型的文章 API,并将所有这些规则放入 Casbin 策略文件中。相同的模型和策略在本教程的 Node.js 和 Python 版本中无需修改即可使用。如果你仍在 RBAC 和 ABAC 之间做选择,请先阅读 选择访问控制模型。
1. 安装
需要 Go 1.22 或更高版本以支持 http.ServeMux 中的方法和通配符模式。
go mod init example.com/abac
go get github.com/casbin/casbin/v3
2. 编写模型
将其保存为 model.conf:
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub_rule, obj_type, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.obj.Type == p.obj_type && r.act == p.act && eval(p.sub_rule)
- 这里的
r.sub和r.obj不是字符串,而是 Go 结构体。匹配器读取它们的字段,例如r.obj.Type。 - 每条策略规则都在
sub_rule中携带一个条件。eval(p.sub_rule)针对请求评估该条件,因此规则存在于策略中而不是模型中。
3. 编写策略
将其保存为 policy.csv:
p, r.obj.Status == 'published', article, read
p, r.sub.Name == r.obj.Owner, article, read
p, r.sub.Name == r.obj.Owner && r.obj.Status == 'draft', article, update
p, r.sub.Role == 'editor' && r.sub.Department == r.obj.Department, article, update
p, r.sub.Role == 'editor' && r.sub.Department == r.obj.Department, article, publish
将每一行读作“当条件为真时,允许对文章执行此操作”:
- 任何人都可以阅读已发布的文章。
- 作者可以阅读自己的文章,包括草稿。
- 作者可以在文章处于草稿状态时编辑自己的文章。
- 编辑人员可以编辑自己部门的任何文章。
- 编辑人员可以发布自己部门的文章。
在条件中使用单引号编写字符串字面量,例如 'published'。字段中间的 double quote 会破坏 CSV 解析。如果条件需要逗号,请用双引号包裹整个字段。
4. 编写服务器
ABAC 需要资源本身,而不仅仅是其 URL,因此检查是在文章加载后运行的。authorize 辅助函数执行此操作,并在答案为否时写入错误响应。
package main
import (
"encoding/json"
"log"
"net/http"
"sync"
"github.com/casbin/casbin/v3"
)
type User struct {
Name string
Role string
Department string
}
type Article struct {
ID string `json:"id"`
Type string `json:"-"`
Title string `json:"title"`
Owner string `json:"owner"`
Department string `json:"department"`
Status string `json:"status"`
}
// In a real application these come from your database.
var users = map[string]User{
"alice": {Name: "alice", Role: "author", Department: "engineering"},
"bob": {Name: "bob", Role: "editor", Department: "engineering"},
"carol": {Name: "carol", Role: "editor", Department: "sales"},
"dave": {Name: "dave", Role: "author", Department: "engineering"},
}
var (
mu sync.Mutex
articles = map[string]*Article{
"1": {ID: "1", Type: "article", Title: "Draft by alice", Owner: "alice", Department: "engineering", Status: "draft"},
"2": {ID: "2", Type: "article", Title: "Published by alice", Owner: "alice", Department: "engineering", Status: "published"},
}
)
type server struct {
e *casbin.Enforcer
}
// authorize loads the current user and asks Casbin whether they may perform act on the article.
func (s *server) authorize(w http.ResponseWriter, r *http.Request, a *Article, act string) bool {
// Replace this with the user from your session or JWT.
user, ok := users[r.Header.Get("X-User")]
if !ok {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return false
}
allowed, err := s.e.Enforce(user, *a, act)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
}
if !allowed {
http.Error(w, "forbidden", http.StatusForbidden)
return false
}
return true
}
func (s *server) article(w http.ResponseWriter, r *http.Request) *Article {
mu.Lock()
defer mu.Unlock()
a, ok := articles[r.PathValue("id")]
if !ok {
http.NotFound(w, r)
return nil
}
return a
}
func main() {
e, err := casbin.NewEnforcer("model.conf", "policy.csv")
if err != nil {
log.Fatal(err)
}
s := &server{e: e}
mux := http.NewServeMux()
mux.HandleFunc("GET /articles/{id}", func(w http.ResponseWriter, r *http.Request) {
a := s.article(w, r)
if a == nil || !s.authorize(w, r, a, "read") {
return
}
json.NewEncoder(w).Encode(a)
})
mux.HandleFunc("PUT /articles/{id}", func(w http.ResponseWriter, r *http.Request) {
a := s.article(w, r)
if a == nil || !s.authorize(w, r, a, "update") {
return
}
mu.Lock()
json.NewDecoder(r.Body).Decode(&struct {
Title *string `json:"title"`
}{&a.Title})
mu.Unlock()
json.NewEncoder(w).Encode(a)
})
mux.HandleFunc("POST /articles/{id}/publish", func(w http.ResponseWriter, r *http.Request) {
a := s.article(w, r)
if a == nil || !s.authorize(w, r, a, "publish") {
return
}
mu.Lock()
a.Status = "published"
mu.Unlock()
json.NewEncoder(w).Encode(a)
})
log.Fatal(http.ListenAndServe(":8080", mux))
}
Casbin 通过反射读取结构体字段,因此在策略中使用的字段(Name、Owner、Status 等)必须是导出的。
X-User 头使示例保持简短。Casbin 仅处理授权;在真实应用中,用户来自你的身份验证层,例如经过验证的 JWT 或会话。
5. 试一试
go run .
文章 1 是 alice 的草稿,文章 2 是她已发布的文章,两者都属于工程部门。
curl -i -H "X-User: dave" http://localhost:8080/articles/1 # 403, someone else's draft
curl -i -H "X-User: dave" http://localhost:8080/articles/2 # 200, published
curl -i -X PUT -H "X-User: alice" -d '{"title":"New title"}' \
http://localhost:8080/articles/1 # 200, her own draft
curl -i -X PUT -H "X-User: alice" -d '{"title":"x"}' \
http://localhost:8080/articles/2 # 403, no longer a draft
curl -i -X PUT -H "X-User: bob" -d '{"title":"x"}' \
http://localhost:8080/articles/2 # 200, editor in engineering
curl -i -X PUT -H "X-User: carol" -d '{"title":"x"}' \
http://localhost:8080/articles/2 # 403, editor in sales
curl -i -X POST -H "X-User: alice" http://localhost:8080/articles/1/publish # 403, authors cannot publish
curl -i -X POST -H "X-User: bob" http://localhost:8080/articles/1/publish # 200
curl -i -H "X-User: dave" http://localhost:8080/articles/1 # 200, now published
6. 在运行时更改规则
条件就是策略行,因此可以在服务器运行时添加和删除它们,并通过 适配器 保存到数据库中:
// Admins may edit any article.
e.AddPolicy("r.sub.Role == 'admin'", "article", "update")
// Nobody may publish any more.
e.RemoveFilteredPolicy(1, "article", "publish")
要找出哪条规则允许了某个请求,请使用 EnforceEx。它返回匹配的规则,这对审计日志很有用:
ok, rule, _ := e.EnforceEx(users["bob"], *articles["2"], "update")
// true [r.sub.Role == 'editor' && r.sub.Department == r.obj.Department article update]
ABAC 还是 RBAC?
- 当权限遵循职位职能且不依赖于正在访问的具体记录时,请使用 RBAC。它更易于审计:“列出编辑人员可以执行的所有操作”是一个简单的查询。请参阅 Go 中的 RBAC 教程。
- 当决策取决于记录本身(如所有者、部门、状态或敏感级别)时,请使用 ABAC。
- 大多数应用程序会结合使用两者:角色决定用户可以访问哪些功能,而属性则进一步缩小范围,确定他们可以操作哪些记录。访问控制模型比较展示了一个组合模型。
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.