Fine-Grained Authorization: RBAC, ABAC and ReBAC
On this page
Learning Objective
Recognize when role checks are no longer enough, compare RBAC, ABAC and relationship-based models, model permissions as relationships with a policy engine such as OpenFGA, solve the list-filtering problem, and test authorization exhaustively with deny by default.
Concept Explanation
Day 47 built authorization from roles, claims, policies, and resource-based checks, and that is enough for many products. It strains when the questions become: can this user edit this document, which lives in a folder shared with a team the user belongs to, unless it is marked confidential? Roles alone cannot express per-resource sharing, and if you keep adding role names to fit, they multiply into hundreds. Broken access control has been the top category of the OWASP Top 10 since the 2021 edition, so it is worth choosing a model deliberately.
Three models cover most needs. Role-based access control assigns permissions to roles and roles to users, simple to understand and audit, but coarse. Attribute-based access control makes decisions from attributes of the user, the resource, and the context, such as department equals finance and time within office hours, which is flexible but can be hard to reason about and test as rules accumulate. Relationship-based access control expresses permissions as relationships in a graph: Anne is an editor of a project, the project is in a folder, the folder is owned by a team, and Anne is a member of the team, so she can view documents in the folder through inheritance. Google published its Zanzibar system in 2019, which stores such relationships to answer authorization for services including Drive, Calendar, and YouTube, and open-source systems such as OpenFGA and SpiceDB follow its ideas. Policy languages such as Cedar and Open Policy Agent's Rego express rules as code evaluated by an engine.
A relationship-based engine has two operations. A check asks whether a user has a relation to an object, and it is fast and used for actions on one item. The harder one is listing: which projects can this user see, needed for every list screen. Doing a check per row is slow and cannot be paginated, and fetching everything and filtering afterward is unsafe and wasteful. Options are asking the engine to list the objects a user can access and then querying your database with those ids, storing permission data next to your rows so that a normal SQL join filters, or pushing a filter into the query. For a moderate-size product, a well-indexed permission table in SQL Server and one authorization function used everywhere is often simpler than a separate service, and a dedicated engine earns its place as the model and scale grow. Whichever you use, funnel every decision through one place, so rules are not scattered through endpoints.
Authorization systems have hard problems of their own. Consistency matters: if a user's access is revoked and then a sensitive document is added, a stale read might still allow access, which Zanzibar addresses with consistency tokens, described as solving the new enemy problem. Caching improves speed but delays revocation. Every decision should default to deny when information is missing, be logged with the inputs, for audit, and be covered by tests, since a matrix of user, action, and resource cases is easy to generate and catches regressions. Remember also that UI checks are conveniences, and the API check is the one that counts, as Day 47 established.
| Model | Strength | Weakness |
|---|---|---|
| RBAC | Simple, easy to audit | Coarse, role explosion for per-resource sharing |
| ABAC | Flexible rules on attributes and context | Rules interact and become hard to reason about |
| ReBAC | Natural for sharing, hierarchies and teams | Needs a store of relationships and a listing strategy |
| Policy engine (Cedar, OPA) | Rules as reviewable, testable code | Data still has to be supplied to the engine |
| Database permission table | Simple, joins filter lists directly | You build inheritance and tooling yourself |
| Central authorization function | One place to change and test | Must be used by every code path |
Worked Example: An OpenFGA Model, Checks and Lists, and an Authorization Matrix Test
The model defines relations. The C# shows a check, a list using engine results, and a test that covers a matrix of cases.
model
schema 1.1
type user
type team
relations
define member: [user]
type project
relations
define owner: [user]
define editor: [user, team#member] or owner
define viewer: [user, team#member] or editor
define can_edit: editor
define can_view: viewer
type task
relations
define parent: [project]
define can_edit: can_edit from parent
define can_view: can_view from parentpublic sealed class Authz(OpenFgaClient fga, ILogger<Authz> log)
{
// A single check. Deny by default: an error or missing data is never treated as allowed.
public async Task<bool> CanAsync(string userId, string relation, string type, string id, CancellationToken ct)
{
try
{
var res = await fga.Check(new ClientCheckRequest { User = $"user:{userId}", Relation = relation, Object = $"{type}:{id}" }, cancellationToken: ct);
log.LogInformation("authz {User} {Relation} {Object} => {Allowed}", userId, relation, $"{type}:{id}", res.Allowed); // decisions are auditable
return res.Allowed == true;
}
catch (Exception ex) { log.LogError(ex, "Authorization check failed, denying"); return false; }
}
// Listing: ask the engine which projects the user may view, then read them from the database with those ids.
public async Task<IReadOnlyList<int>> ViewableProjectIdsAsync(string userId, CancellationToken ct)
{
var res = await fga.ListObjects(new ClientListObjectsRequest { User = $"user:{userId}", Relation = "can_view", Type = "project" }, cancellationToken: ct);
return res.Objects.Select(o => int.Parse(o["project:".Length..])).ToList();
}
}
// One endpoint: check, then act. The check is the same function used everywhere.
app.MapPut("/api/tasks/{id:int}", async (int id, UpdateTask body, Authz authz, ClaimsPrincipal user, AppDb db, CancellationToken ct) =>
{
if (!await authz.CanAsync(user.GetUserId(), "can_edit", "task", id.ToString(), ct)) return Results.NotFound(); // do not reveal existence
/* update */
return Results.NoContent();
});
// Keeping the engine in step with the database: writing a relationship is part of the same workflow as creating the project.
await fga.Write(new ClientWriteRequest { Writes = [new ClientTupleKey { User = $"user:{ownerId}", Relation = "owner", Object = $"project:{project.Id}" }] });-- The simpler alternative for a moderate product: a permission table that ordinary queries can join.
CREATE TABLE dbo.ProjectAccess (ProjectId int NOT NULL, PrincipalId uniqueidentifier NOT NULL, Role tinyint NOT NULL,
CONSTRAINT PK_ProjectAccess PRIMARY KEY (ProjectId, PrincipalId));
CREATE INDEX IX_ProjectAccess_Principal ON dbo.ProjectAccess (PrincipalId) INCLUDE (ProjectId, Role);
-- List: SELECT p.* FROM dbo.Projects p JOIN dbo.ProjectAccess a ON a.ProjectId = p.Id WHERE a.PrincipalId = @user;// The authorization matrix: users, actions and resources enumerated in a table, so a change that widens access fails a test.
[Theory]
[InlineData("anne", "can_edit", "project:1", true)] // owner
[InlineData("bob", "can_edit", "project:1", false)] // viewer through the design team
[InlineData("bob", "can_view", "project:1", true)]
[InlineData("carol", "can_view", "project:1", false)] // no relationship at all
[InlineData("bob", "can_view", "task:9", true)] // inherited from its project
[InlineData("carol", "can_edit", "task:9", false)]
public async Task Matrix(string user, string relation, string obj, bool expected)
{
var parts = obj.Split(':');
Assert.Equal(expected, await authz.CanAsync(user, relation, parts[0], parts[1], CancellationToken.None));
}The choice between the engine and the table is a matter of how many kinds of relationships you have. Start with the table and one function, and move to an engine when inheritance across several levels and sharing rules make the table logic the hardest part of the codebase.
Real-World Examples
- Google's 2019 paper on Zanzibar described a global authorization system storing trillions of access control lists and serving millions of checks per second for products such as Drive, Calendar, Photos, and YouTube. Its design goals of consistency, low latency, and a single shared model are the source of most modern relationship-based authorization tools.
- The OWASP Top 10 moved Broken Access Control to first place in its 2021 edition, based on data showing it in a large share of tested applications, and broken object level authorization holds the top position in the API Security Top 10. The recurring cause is checks that are missing, inconsistent, or scattered, which is the argument for a central decision point.
Review Questions & Answers
They express per-resource sharing and inheritance, such as access through team membership and folder hierarchy, without inventing a new role for every combination. The permission is derived from relationships in a graph.
Checking each row individually is slow and breaks pagination, and loading everything and filtering afterward is wasteful and can leak counts. The system must produce the set of accessible ids or a filter that the database query can apply directly.
If the decision cannot be made, because data is missing or the service errors, the answer is no. This prevents an outage or a gap in the rules from silently granting access.
Access control regressions are usually a case that quietly became allowed, and a table of expected results makes every case visible. A change that widens access then fails a specific, named test.