Mastering Casbin: Build Secure RBAC in Go with Gin and Gorm
This article explains what Casbin is, how its PERM model works, and provides a step‑by‑step guide to integrate Casbin’s RBAC authorization into a Go project using Gin, Gorm, and a MySQL adapter, including model configuration, policy storage, middleware enforcement, and verification.
What is Casbin
Casbin is a powerful, efficient open‑source access‑control framework that supports multiple models. It handles only authorization.
Features include:
Custom request format, default {subject, object, action} Core concepts: model and policy
Multi‑level role inheritance for subjects and resources
Built‑in super‑user (e.g., root or administrator) that bypasses explicit policies
Built‑in operators such as keyMatch for path‑style resources (e.g., /foo/bar matches /foo*)
How Casbin Works
Casbin abstracts the access‑control model into four components—Policy, Effect, Request, Matcher (PERM). Policies define rules, matchers compare requests to policies, and effects determine whether the result is allow or deny.
Policy: defines permission rules
Effect: combines multiple policies
Request: the access request
Matcher: decides if a request satisfies a policy
Core Concepts
Model
The model is described in a .conf file that must contain at least four sections: [request_definition], [policy_definition], [policy_effect], [matchers]. When using RBAC, a [role_definition] section is also required. Comments start with #.
# Request definition
[request_definition]
r = sub, obj, act
# Policy definition
[policy_definition]
p = sub, obj, act
# Role definition
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.sub == p.sub && ParamsMatch(r.obj,p.obj) && r.act == p.act request_definitiondefines
sub, obj, act policy_definitiondefines rules such as
p, alice, data1, read role_definitiondefines role inheritance with
g, _, _ policy_effectdecides the final effect, e.g.,
e = some(where (p.eft == allow)) matchersare expressions that match requests to policies
Policy
Policy maps subjects, objects, and actions. Policies can be stored in CSV files or loaded via adapters (MySQL, PostgreSQL, SQLite, MongoDB, Redis, Cassandra, etc.). Example:
p, alice, data1, read
p, bob, data2, write
p, data2_admin, data2, read
p, data2_admin, data2, write
g, alice, data2_adminPractical Implementation
Create Project
Initialize a Go module named casbin_test with the following directory layout:
├─configs # configuration files
├─global # global variables
├─internal
│ ├─dao # data access
│ ├─middleware# middleware
│ ├─model # model layer
│ ├─router # routing
│ │ └─api
│ │ └─v1
│ └─service # business logic
├─pkg
│ ├─app
│ ├─errcode
│ └─settingInstall dependencies:
go get -u github.com/gin-gonic/gin
go get github.com/casbin/casbin
go get github.com/casbin/gorm-adapter
go get github.com/go-sql-driver/mysql
go get github.com/jinzhu/gormCreate the MySQL database casbin_test and the casbin_rule table as shown.
Code Development
Key files include: configs/rbac_model.conf – model definition internal/model/casbin.go – Gorm model and CRUD methods internal/dao/casbin.go – DAO functions internal/service/service.go – service layer for creating and listing policies internal/router/api/v1/casbin.go – HTTP handlers with Swagger annotations internal/middleware/casbin_handler.go – middleware that enforces policies using
e.Enforce(sub, obj, act) internal/router/router.go– router setup with Casbin middleware
Verification
After launching the service, test the protected endpoint, add the path to the policy list, and observe that the request is allowed only after the policy is present.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development Stories
Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
