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.