ABAC in Go
Role-based access control answers "what may an editor do?". Many real rules need more than a role: authors may edit their own drafts, editors may edit articles from their own department, anyone may read a published article. These depend on attributes of the user and of the resource, which is what attribute-based access control (ABAC) is for.
This tutorial builds a small article API in Go with the standard net/http package and puts all of those rules in a Casbin policy file. The same model and policy work unchanged in the Node.js and Python versions of this tutorial. If you are still choosing between RBAC and ABAC, read Choosing an access control model first.
1. Install
Go 1.22 or later is needed for the method and wildcard patterns in http.ServeMux.
go mod init example.com/abac
go get github.com/casbin/casbin/v3
2. Write the model
Save this as 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.subandr.objare not strings here but Go structs. The matcher reads their fields, such asr.obj.Type.- Each policy rule carries a condition in
sub_rule.eval(p.sub_rule)evaluates that condition against the request, so the rules live in the policy instead of in the model.
3. Write the policy
Save this as 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
Read each line as "allow this action on articles when the condition is true":
- Anyone may read a published article.
- Authors may read their own articles, including drafts.
- Authors may edit their own articles while they are drafts.
- Editors may edit any article from their own department.
- Editors may publish articles from their own department.
Write string literals in conditions with single quotes, as in 'published'. A double quote in the middle of a field breaks CSV parsing. If a condition needs a comma, wrap the whole field in double quotes.