A new teacher starts at Siti's school. The Portal admin doesn't tick permissions one by one for her: picking the teacher role is enough, and every teacher permission is included.
That's how RBAC (Role-Based Access Control) works: permissions are granted through a role, not to each person one by one. A school caretaker does the same with keys. He doesn't cut new keys for every teacher who arrives. He has one key ring per position. The "teacher" ring holds the classroom and staff-room keys. The "head teacher" ring holds all of those, plus the archive key. A new teacher just gets the "teacher" ring. In RBAC, the caretaker is the Portal admin, the new teacher is a user, the ring is the role, each key is a permission (the right to do one kind of action), and the doors are the routes on the server.
User, role, permission
The first lesson of this track already gave School Portal three roles. Now we arrange them more neatly: each role holds its own permissions, then inherits the permissions of the lower role.
| Role | Own permissions | Inherits | All its permissions |
|---|---|---|---|
student (Siti) |
grades:read |
grades:read |
|
teacher (Mr. Andi) |
grades:write |
student |
grades:read, grades:write |
admin (Mrs. Dewi) |
users:delete |
teacher |
grades:read, grades:write, users:delete |
Why through roles? Imagine the Portal has 1,000 students. If permissions are given to each user, adding one permission for every student means 1,000 changes, and some will be missed. With roles, you change the student role once, and every student has that permission at their next request. Auditing (checking who may do what) is easy too: "who may delete users?" is answered by looking at one list.
There is also the term permission-based access control (PBAC): what gets checked is a specific permission such as grades:write, not the role's name. Most apps combine the two, exactly like the Portal: a user has a role, a role holds permissions, and the code checks the permission. So write can("grades:write"), not role === "teacher". If the deputy head may also enter grades tomorrow, the code needs no change. You only give that permission to the deputy head's role.
Role inheritance
The list of what each role inherits (this.hierarchy) is kept apart from the permission lists (this.roles). To calculate every permission of a role, take its own permissions, then follow the roles it inherits from, until there are none left:
class RBAC {
constructor() {
this.roles = {}; // { role: [own permissions] }
this.hierarchy = {}; // { role: [roles it inherits from] }
}
addRole(roleName, permissions) {
this.roles[roleName] = permissions;
}
setHierarchy(roleName, inheritsFrom) {
if (!this.hierarchy[roleName]) this.hierarchy[roleName] = [];
this.hierarchy[roleName].push(inheritsFrom);
}
getAllPermissions(roleName) {
const all = new Set(this.roles[roleName] || []);
for (const parent of this.hierarchy[roleName] || []) {
this.getAllPermissions(parent).forEach((p) => all.add(p)); // inheritance down the chain
}
return [...all].sort();
}
can(roleName, permission) {
return this.getAllPermissions(roleName).includes(permission);
}
}
const rbac = new RBAC();
rbac.addRole("student", ["grades:read"]);
rbac.addRole("teacher", ["grades:write"]);
rbac.addRole("admin", ["users:delete"]);
rbac.setHierarchy("teacher", "student");
rbac.setHierarchy("admin", "teacher");
console.log(rbac.can("teacher", "grades:read")); // true, inherited from student
console.log(rbac.can("student", "grades:write")); // false, inheritance goes one way only
console.log(rbac.getAllPermissions("admin").join(",")); // grades:read,grades:write,users:delete
this.hierarchy[roleName]is an array, so one role can inherit from more than one role.getAllPermissionscalls itself (it is recursive): admin asks teacher, teacher asks student. That way the inheritance is followed to the end of the chain.new Set(...)drops duplicate permissions,[...all]turns it back into an array, and.sort()puts it in alphabetical order (A to Z).|| []handles an unknown role: the result is an empty array, socanreturnsfalseinstead of throwing an error.
The trace of getAllPermissions("admin"):
| Step | Role | Own permissions | Collected so far |
|---|---|---|---|
| 1 | admin |
users:delete |
users:delete |
| 2 | teacher (inherited by admin) |
grades:write |
users:delete, grades:write |
| 3 | student (inherited by teacher) |
grades:read |
users:delete, grades:write, grades:read |
| sort | grades:read, grades:write, users:delete |
Inheritance goes one way only: teacher inherits student, not the other way round.
Checking on the server: middleware
The check is placed as middleware in front of the route, so it runs before the handler (the function that does the route's work). The handler doesn't have to remember to check. This example uses the Express style, a server framework for JavaScript:
function requirePermission(permission) {
return (req, res, next) => {
if (!req.user) return res.status(401).json({ message: "Unauthenticated." });
if (!rbac.can(req.user.role, permission)) {
return res.status(403).json({ message: "This action is unauthorized." });
}
next();
};
}
app.post("/grades", requirePermission("grades:write"), storeGrade);
app.delete("/users/:id", requirePermission("users:delete"), deleteUser);
req.user is the user who is logged in. If it is empty, nobody is logged in, so the answer is 401. If the role doesn't have that permission, the answer is 403. If the check passes, next() passes the request on to the handler, such as storeGrade.
Mrs. Dewi sends POST /grades: admin doesn't own grades:write, but inherits it through teacher, so the answer is 201 Created. Siti sends the same request: 403 Forbidden.
Hiding the button vs refusing on the server
On the report page, the Portal's interface (built with React) hides the "Enter a grade" button when can("grades:write") is false. That is good design: Siti doesn't see a button she can't use. But a request needs no button. Siti can send POST /grades from DevTools, Postman or curl, tools that can send a request directly, with no button on the page. The only thing that stops it is the check on the server, which answers 403. So hiding the button alone is not enough. The server decides every permission. In the Lab, turn the server check off and send it again as Siti: the grade is saved, though the button isn't there.
In Laravel: Gate, the can middleware, Policy
Laravel has a tool for each of these parts:
// app/Providers/AppServiceProvider.php, in the boot() method
foreach (['grades:read', 'grades:write', 'users:delete'] as $permission) {
Gate::define($permission, fn (User $user) => in_array($permission, Rbac::permissionsOf($user->role), true));
}
// routes/api.php
Route::post('/grades', [GradeController::class, 'store'])->middleware(['auth:api', 'can:grades:write']);
Route::delete('/users/{user}', [UserController::class, 'destroy'])->middleware(['auth:api', 'can:users:delete']);
Gate::defineregisters one Gate per permission: a check rule that Laravel also calls an ability.Rbac::permissionsOf(...)is a helper of this app that calculates a role's permissions with its inheritance, likegetAllPermissions.- The
can:grades:writemiddleware runs thegrades:writeGate before the controller (the Laravel code that does the route's work), and answers403when it fails. - In Blade (Laravel's HTML templates), or in an API that tells the frontend,
$user->can('grades:write')decides which buttons to show. The server still checks through the middleware.
For a permission that depends on the record, such as a student reading only her own report, use a Policy. A policy gets the user and the record being accessed:
// app/Policies/UserPolicy.php
public function viewGrades(User $user, User $student): bool
{
return $user->can('grades:read') && ($user->role !== 'student' || $user->is($student));
}
// in the controller for GET /students/{student}/grades
Gate::authorize('viewGrades', $student); // fails: 403
So the user must have grades:read. If the user is a student, $student must also be that same user ($user->is($student)). More detailed rules (the classes someone teaches, school hours) are covered in the RBAC vs ABAC: Implementation lesson.
⚠️ Permission code that looks like it works, but doesn't yet
- Checking permissions only on the frontend. The frontend is the code that runs in the browser, and a request can be sent without its buttons. Put middleware on every route.
- Checking the role's name in code (
role === "admin"). As soon as there is a new role, every one of thoseifs has to be found and changed. Check the permission. - Forgetting inheritance down the chain. If
getAllPermissionslooks only one level up, admin doesn't getgrades:readfrom student. Keep following it with recursion. - Duplicate or unsorted permissions. Combine them with a
Set, then.sort(), so the result is tidy and easy to compare.
TL;DR: RBAC (Role-Based Access Control): a user has a role, and a role has permissions (a permission allows one kind of action). Permissions change on the role, not on each user: 1,000 students, one change. A role can inherit another role. getAllPermissions takes the role's own permissions, then the inherited ones recursively (the function calls itself). The result has no duplicates (Set) and is sorted (.sort()), and can checks the permission in that result. Code checks the permission (grades:write), not the role name. The decision is made on the server: middleware answers 403, while hiding a button only changes what the page shows. In Laravel: Gate::define, the can:... middleware, and a Policy for permissions that depend on the record.
⚡ Permissions through a role
Meaning: In RBAC (Role-Based Access Control), permissions are granted through a role, not to each person one by one. A user has a role, and a role has permissions (a permission allows one kind of action). School Portal has 1,000 students and all of them need one new permission? Change the student role once.
⚡ Check the permission, not the role name
Meaning: What the code checks is the specific permission (permission-based, PBAC), such as grades:write, the permission to enter grades. Write can("grades:write") (it checks whether the user has that permission), not role === "teacher". If the deputy head may also enter grades tomorrow, the code needs no change. You only give that permission to the deputy head's role.
⚡ Inheritance down the chain
Write:
getAllPermissions(roleName) {
const all = new Set(this.roles[roleName] || []);
for (const parent of this.hierarchy[roleName] || []) {
this.getAllPermissions(parent).forEach((p) => all.add(p)); // inheritance down the chain
}
return [...all].sort();
}
Guess first: student has grades:read, and teacher has grades:write and inherits student. What does rbac.can("student", "grades:write") give?
false. Inheritance goes one way only: teacher inherits student, not the other way round.
Meaning: this.roles holds each role's own permissions, and this.hierarchy holds the roles it inherits (parent). getAllPermissions calls itself (recursion) for each inherited role. So if admin inherits teacher, admin gets teacher's permissions, and through teacher, student's too. Set drops duplicates, .sort() puts them in order.
⚡ The server decides
Meaning: Hiding the "Enter a grade" button from Siti, a student, only changes what the page shows. Siti can still send POST /grades (the request that saves a grade) from DevTools or curl, tools that send a request with no button on the page. The only thing that stops it is the middleware on the server, which answers 403.