RBAC assigns permissions to roles and checks the active role for each protected action.
What It Does
RBAC assigns permissions to roles and checks the active role for each protected action. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Map roles to explicit permissions rather than checking display labels.
<?php
$rolePermissions = ["reader" => ["read"], "editor" => ["read", "write"]];
$role = "editor";
echo in_array("write", $rolePermissions[$role] ?? [], true) ? "Can edit" : "Forbidden";
Example 2: Another Case
Default deny when a role does not have an explicitly assigned permission.
<?php
function allowedRole(string $role, string $permission): bool { $matrix = ["admin" => ["export", "edit"], "guest" => []]; return in_array($permission, $matrix[$role] ?? [], true); }
var_dump(allowedRole("guest", "export"));
Practical Example: Putting It to Use
RBAC alone is not sufficient for multi-tenant data isolation.
<?php
$actor = ["role" => "editor", "tenant_id" => 4]; $document = ["tenant_id" => 5];
$allowed = $actor["role"] === "editor" && $actor["tenant_id"] === $document["tenant_id"];
var_dump($allowed);
Important Behavior and Edge Cases
Roles alone cannot express tenant ownership or record-specific rules; reject by default.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Applying Role-Based Access Control | RBAC assigns permissions to roles and checks the active role for each protected action. |
| Related approach | Add object-level authorization when a role spans multiple users or resources. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Applying Role-Based Access Control | Roles alone cannot express tenant ownership or record-specific rules; reject by default. |
| Assuming a related mechanism has the same behavior | Add object-level authorization when a role spans multiple users or resources. |
Key Takeaways
- RBAC assigns permissions to roles and checks the active role for each protected action.
- Roles alone cannot express tenant ownership or record-specific rules; reject by default.
- Add object-level authorization when a role spans multiple users or resources.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.