Roles and permissions explained, with Go examples
Authentication answers "who is this". Authorisation answers "may they do that". Role-based access control is one way to answer the second: give people roles, give roles permissions, and check the permission rather than the person.
It is genuinely simple. What is not simple, and what this page spends most of its time on, is that a role check alone answers the wrong question in about half the cases you will meet.
14 min read. Commands and output last run against Grit v3.560.0.
What you will have at the end
Roles and permissions in a Go API, with the check in one place rather than scattered.
A clear grasp of why "can this user edit invoices" and "can this user edit this invoice" are different questions needing different code.
The status code to return, and why the obvious one is the wrong one.
The idea, in one paragraph
A hotel does not program each guest's keycard individually. It has card types: guest, cleaner, manager. A guest card opens one room, the pool and the gym. A cleaner card opens every room but not the safe. Reception issues a type, not a list of doors, and when the rules change they change the type rather than three hundred cards.
That is the whole of RBAC. Three pieces: a permission is one thing you may do, such as invoice.delete. A role is a named bundle of permissions. A user has one or more roles. Code checks the permission and never the role.
Check the permission, not the role
if user.Role == "admin" scattered through your handlers is a policy you cannot change. The day you add a "support" role that may also refund an order, you are grepping for every place admin was assumed. Checking order.refund instead means the change is one row in a table.
The data model
Start with the simplest thing that works. One role per user, with permissions derived in code, is enough for a surprising number of real applications.
package authztype Permission stringconst (UserRead Permission = "user.read"UserWrite Permission = "user.write"InvoiceRead Permission = "invoice.read"InvoiceWrite Permission = "invoice.write"InvoiceDelete Permission = "invoice.delete"SettingsWrite Permission = "settings.write")// What each role may do. The whole policy, in one readable place, which is// the point: a reviewer can see the system's rules without reading handlers.var rolePermissions = map[string][]Permission{"admin": {UserRead, UserWrite,InvoiceRead, InvoiceWrite, InvoiceDelete,SettingsWrite,},"editor": {UserRead,InvoiceRead, InvoiceWrite,},"viewer": {UserRead,InvoiceRead,},}func Can(role string, p Permission) bool {for _, held := range rolePermissions[role] {if held == p {return true}}return false}
Move it into the database when the people who decide the rules are not the people who deploy. That is the real trigger, not scale: a table means a screen, and a screen means an administrator can grant something at four in the afternoon without a release.
Where the check goes
On the route, as middleware, not inside the handler. A handler that both checks permissions and does work has two reasons to change, and the check is easy to omit on the next handler somebody adds.
func Require(p authz.Permission) gin.HandlerFunc {return func(c *gin.Context) {role, _ := c.Get("role") // put there by the auth middlewareif !authz.Can(role.(string), p) {c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": gin.H{"code": "FORBIDDEN","message": "you do not have permission to do that",}})return}c.Next()}}
invoices := r.Group("/api/invoices", middleware.Auth(secret)){invoices.GET("", middleware.Require(authz.InvoiceRead), h.List)invoices.GET("/:id", middleware.Require(authz.InvoiceRead), h.Get)invoices.POST("", middleware.Require(authz.InvoiceWrite), h.Create)invoices.PATCH("/:id", middleware.Require(authz.InvoiceWrite), h.Update)invoices.DELETE("/:id", middleware.Require(authz.InvoiceDelete), h.Delete)}
Read that block and you know the policy for invoices. That readability is worth as much as the mechanism: an access rule you cannot see is an access rule nobody reviews.
The half that roles cannot answer
This is the important part of the page.
Your editor has invoice.write. The middleware lets them through. They send PATCH /api/invoices/8821, and invoice 8821 belongs to a different customer.
Nothing above stops that, and nothing above is wrong. The role check answered "may this user edit invoices", correctly, with yes. Nobody asked whether they may edit this invoice, because that question needs the row, and the middleware ran before anybody had loaded it.
This is the vulnerability class with the clumsy name, insecure direct object reference, and it is consistently among the most common serious findings in web applications. It needs no tooling to exploit: change a number in the URL.
Put the owner in the query
// Wrong: fetch by id, then maybe check. Every "then maybe" is a handler// somebody will write without the second half.var invoice models.Invoicedb.First(&invoice, c.Param("id"))// Right: the scope is part of the query, so a row outside it cannot come// back at all. There is no second step to forget.err := db.Where("id = ? AND organisation_id = ?", c.Param("id"), orgID).First(&invoice).Error
The difference matters because of what happens when somebody is careless. In the first version, forgetting the check returns the row. In the second, forgetting the scope is a missing argument the compiler complains about, or at worst a query that returns nothing. Prefer the shape where the mistake fails closed.
Answer 404, not 403
if errors.Is(err, gorm.ErrRecordNotFound) {// Not "forbidden". A 403 confirms invoice 8821 exists, which is half// of what somebody walking the id space wanted to learn. For a row// outside your scope, the honest answer is that there is no such row// as far as you are concerned.c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"code": "NOT_FOUND", "message": "invoice not found",}})return}
Hence the rule worth memorising: a permission failure is 403, a scope failure is 404. The first says "you may not do this kind of thing", which is safe to admit. The second must not distinguish "not yours" from "not there".
Every write path needs the same scope
It is not enough to get the single-record handler right. A bulk edit, an export, a CSV import, a search endpoint and a report all read the same table, and each is a separate way in. One of them written without the scope undoes the others. When you add a new way to reach a table, the question is not whether the code works but whether it carries the same rule.
When roles stop being enough
Roles answer questions about kinds of user. Some questions are about the specific relationship between a user and a thing, and no number of roles will express them:
- "The author may edit their own post, for thirty minutes after publishing."
- "A manager may approve expenses, but not their own."
- "Members of the project may comment; everyone else may read."
Adding a role for each of these produces a role explosion, and a permissions table nobody understands within a year. These belong in a policy: a function that takes the user and the record and returns a decision.
// A policy sees both sides, which is exactly what a role check cannot.func CanEditPost(u *models.User, p *models.Post) bool {if authz.Can(u.Role, authz.PostModerate) {return true}if p.AuthorID != u.ID {return false}return time.Since(p.PublishedAt) < 30*time.Minute}
Keep policies in one package, name them after the action, and test them directly. They are the most security-relevant functions you will write and the cheapest to unit test, because they take two structs and return a boolean.
Test the refusals
Most authorisation test suites check that the permitted case works. That is the case that would have been reported in five minutes anyway. The valuable tests are the refusals, because nobody reports a thing that silently works when it should not.
func TestViewerCannotDeleteInvoice(t *testing.T) {res := request(t, "DELETE", "/api/invoices/1", asRole("viewer"))require.Equal(t, http.StatusForbidden, res.Code)}func TestEditorCannotTouchAnotherOrgsInvoice(t *testing.T) {// Editor in org 1, invoice in org 2: a 404, not a 403, because a 403// would confirm the invoice exists.res := request(t, "PATCH", "/api/invoices/"+otherOrgInvoiceID, asRole("editor"))require.Equal(t, http.StatusNotFound, res.Code)}
Write one of each per protected resource. It is tedious, it is quick, and it is the only way you will notice the day somebody adds a route and forgets the middleware.
How a generated project does it
A Grit project ships roles, a permission map, the middleware and a roles screen in the admin. Per-resource policies live in internal/policies, and ownership scoping is generated rather than remembered:
$grit generate resource Invoice --fields "number:string,total:money" --owned-by user$grit add role support
--owned-by user is the interesting flag: it puts the owner in every query the resource generates, including the list, the bulk edit and the export, so the rule does not depend on whoever writes the next endpoint remembering it.
There is also a static route table in internal/access that records which routes are protected and by what, because a web framework cannot report its own middleware chain at runtime. grit doctor reads it and tells you about a route that has no guard.
The roles and policies reference covers the generated code.
Frequently asked questions
- What is the difference between authentication and authorisation?
- Authentication establishes who is calling, usually with a password and then a token. Authorisation decides whether that person may do the thing they just asked for. They fail differently too: an unauthenticated request is a 401, meaning sign in, and an unauthorised one is a 403, meaning you are signed in and the answer is still no.
- Should roles live in the JWT or be looked up per request?
- In the token is faster and is usually right, with one consequence to accept: a role change does not take effect until the token is refreshed. With a fifteen-minute access token that is a fifteen-minute window, which is fine for a promotion and not fine for an emergency revocation. For the emergency case, revoke the session rather than hoping the role check catches it.
- How many roles should I start with?
- Three: admin, a working role, and a read-only role. Almost every application converges on something like that, and starting with twelve means designing a permission system for requirements you have imagined. Add the fourth when somebody asks for it in words, not when you anticipate it.
- Is RBAC enough, or do I need ABAC?
- RBAC covers questions about kinds of user and gets you a long way. Attribute-based rules, decisions that depend on the record, the time or the relationship, are better expressed as policy functions than as a general attribute engine. Reach for a full policy engine such as OPA when the rules are genuinely a product feature customers configure, not before.
Next steps
- JWT authentication in GoEstablishing who is calling, which has to happen before any of this.
- Build an admin dashboardWhere roles become a screen somebody other than you can use.
- Roles and policies referenceThe generated permission map, per-resource policies and the route table.
- Authorization in depthScoping, the 403 against 404 rule, and what grit doctor checks.
