Permission Models Deep Dive: ACL, RBAC 0-3 & ABAC with Implementation
This comprehensive guide explores access control models from basic ACL through RBAC's four layers to attribute-based ABAC, with practical code examples for role inheritance, separation of duties, and data-level permission implementation using annotations and AOP.
Introduction
The author illustrates permission system evolution through a developer "Xiao A" who built three versions: hardcoded role checks, direct user-permission mapping, and finally RBAC. Each version exposed new limitations — hardcoded roles required code changes for each new role; direct permission mapping caused maintenance explosion; RBAC solved batch management but couldn't express conditions like "view only own department data" or "work hours only access."
Concept Definitions
2.1 What Is a Permission Model
Definition: A permission model is an abstract framework describing the authorization relationship where a Subject performs an Action on an Object/Resource . It defines how permissions are organized, assigned, and validated.
In plain terms: It answers "who can do what to which thing." It specifies how "who" (user/role), "what thing" (resource), and "do what" (read/write/delete) relate and are evaluated.
2.2 Three Core Elements
Subject — Actor initiating the operation (e.g., user, service account)
Object/Resource — Target being operated on (e.g., order, user, menu, button)
Action — Operation on the resource (e.g., view, create, update, delete)
The essence of a permission is a tuple: Subject can perform Action on Object .
2.3 Mainstream Permission Models Overview
ACL (Access Control List) — Directly list "who can access" per resource; applicable to file systems, simple resources.
RBAC (Role-Based Access Control) — User ↔ Role ↔ Permission; applicable to most business systems.
ABAC (Attribute-Based Access Control) — Dynamic decision based on subject/object/environment attributes; applicable to complex conditions, data-level permissions.
PBAC (Policy-Based Access Control) — Unified decision via policy engine; applicable to complex enterprise, compliance scenarios.
2.4 Authentication vs Authorization
Authentication (AuthN) — Solves "who are you"; typical tasks: login, identity verification; common means: username/password, SSO, OIDC.
Authorization (AuthZ) — Solves "what can you do"; typical tasks: permission check, resource access control; common means: RBAC, ABAC, ACL.
Relationship: Authentication is a prerequisite for authorization — first know "who you are," then decide "what you can do." This article focuses on authorization (permission models).
Background: Evolution of Permission Models
Each new model emerged to solve bottlenecks of the previous one.
3.1 Evolution Timeline
3.2 Pain Points Solved at Each Stage
ACL → RBAC — ACL ties users directly to resources; maintenance explodes as users grow. Example: file system per-user permissions vs role-based batch authorization.
RBAC0 → RBAC1 — Roles cannot inherit; duplicate definitions. Example: "Operator" and "Team Lead" share many permissions; need inheritance.
RBAC1 → RBAC2 — Cannot express separation of duties. Example: finance "create" and "approve" cannot be same person.
RBAC → ABAC — Cannot express conditional permissions. Example: "view only own department data," "access only during work hours."
ABAC → PBAC — Rules scattered, hard to maintain. Example: centralize rules in policy engine for unified management and audit.
3.3 Why RBAC Is Mainstream
Matches organizational structure: Enterprises naturally divide responsibilities by roles (positions); RBAC maps naturally.
Efficient batch management: Role = position; personnel changes only swap roles, permissions adjust automatically.
Simple and sufficient: 80% of permission needs are expressible as "has/doesn't have this permission point."
Mature ecosystem: Spring Security, Sa-Token, Shiro all have built-in RBAC support.
ABAC and PBAC supplement RBAC — RBAC governs "can you call this API," ABAC governs "which data can you see," PBAC governs "unified decision under complex conditions."
Analogy: Office Building Access Control
Give each person a key to every door → ACL (each person directly linked to each door)
Issue "department badges" for floor access → RBAC (role = badge)
Manager badge automatically includes employee badge rights → RBAC1 (role inheritance)
Finance room "create" and "approve" cards cannot be held by same person → RBAC2 (separation of duties constraint)
Server room requires fingerprint + workday-only entry → ABAC (multi-attribute conditions)
All access rules configured in central system → PBAC (policy engine)
Key takeaways:
ACL is "door finds key": Each door maintains a "who can enter" list; list explodes as people grow.
RBAC is "person finds badge": Person holds badge, badge maps to doors; batch management.
ABAC is "on-site judgment": Not just badge, but time, location, fingerprint — dynamic decision.
PBAC is "central dispatch": All rules configured centrally; each door only "asks central."
Positive and Negative Examples
5.1 Negative Example: Hardcoded Role Checks
// Negative example
if ("admin".equals(user.getRole())) {
return "manage";
} else if ("operator".equals(user.getRole())) {
return "operate";
}Problems:
Role coupled with code; new role requires code change and redeploy.
Single role per user ( role field is single-valued); cannot support "both operator and customer service."
"Team lead views team data" inexpressible.
5.2 Negative Example: User Directly Linked to Permissions
// Negative example: each user manually assigned dozens of permissions
user_permissions table: user_id, permission
1, user:view
1, user:edit
1, order:view
... dozens of rows per userProblems: New hire requires manually checking dozens of permissions; role change requires individual adjustments; maintenance cost explodes. No batch management — adding order:view to all operators means adding one by one.
5.3 Positive Example: Standard RBAC Three Layers
User ↔ Role ↔ Permission. New hire selects "Operator role" to get all operator permissions; adding a new permission to all operators only modifies the role, automatically effective for all.
5.4 Positive Example: ABAC for Conditional Permissions
// "View only own department orders" — RBAC cannot express, use ABAC
@DataScope(dept = "#user.deptId")
public List<Order> listOrders(User user) {
// Framework auto-injects "where dept_id = #{user.deptId}" filter
}Permission is not just "can you order:view " but "only view own department's" — requires dynamic judgment via attributes (department), which is ABAC's domain.
Core 1: ACL Deep Dive
6.1 ACL Principle
ACL (Access Control List) is the most basic permission model: each resource maintains a list of "who can do what to it."
Resource: /file/report.docx
ACL:
- user:1 → read, write
- user:2 → read
- group:finance → read, write6.2 ACL Applicability and Limitations
Pros: Intuitive, easy to understand; fine-grained, precise to single resource; suitable for few, relatively fixed resources.
Cons: List per resource explodes when resources are many; personnel changes require per-resource adjustment; no batch authorization.
Applicable scenarios:
File systems (Linux file owner/group/other permissions)
Cloud resource IAM (per-resource policy)
Object storage (OSS Bucket Policy)
These "few resources, need per-resource precision" scenarios suit ACL.
Not suitable: Enterprise back-office systems (many users, many resources, frequent personnel changes) — ACL maintenance cost explodes; use RBAC instead.
6.3 Essential Difference Between ACL and RBAC
ACL is "resource finds user" — each resource lists accessible users.
RBAC is "user finds resource" — user holds role, role maps to resource permissions.
Significance of perspective shift: Enterprise personnel change frequently, roles relatively stable; "user finds resource" aligns with management habits.
Core 2: RBAC Four-Layer Model Deep Dive
RBAC standard defines four layers (NIST RBAC, INCITS 359-2004), each adding capabilities.
7.1 RBAC0: Basic Three Layers
User — Role — Permission three-layer many-to-many. This is the most common form; 80% of systems stop here.
Core data structures:
User table (sys_user)
Role table (sys_role)
Permission table (sys_permission)
User-Role association table (sys_user_role)
Role-Permission association table (sys_role_permission)
7.2 RBAC1: Role Inheritance
Child role inherits all parent role permissions, can add more. Value: Avoids duplicate definitions — "Team Lead" automatically includes "Operator" permissions, plus management permissions.
Implementation: Add parent_id to role table; recursively merge parent permissions when loading.
/** Recursively expand parent roles (RBAC1 inheritance) */
private Set<Long> expandWithParents(List<Long> roleIds) {
Set<Long> all = new HashSet<>(roleIds);
for (Long roleId : roleIds) {
Long parentId = roleMapper.findParentId(roleId);
while (parentId != null && all.add(parentId)) {
parentId = roleMapper.findParentId(parentId);
}
}
return all;
}Considerations:
Inheritance must avoid cycles (A inherits B, B inherits A); check before assignment.
Multiple inheritance complicates; most systems support only single inheritance (one parent per role).
Inheritance chain shouldn't be too deep, else permission tracing becomes difficult.
7.3 RBAC2: Role Constraints
Most common is Separation of Duties (SoD) :
Static Separation of Duties — "Create" and "Approve" roles cannot be held by same person.
Dynamic Separation of Duties — Same person may hold both, but cannot play both roles in same business process.
Cardinality Constraint — One user max 3 roles.
Prerequisite Constraint — Must have "Operator" before granting "Team Lead".
Static SoD:
/** Check SoD constraint when assigning role */
public void assignRole(Long userId, Long newRoleId) {
// Check if new role conflicts with user's existing roles
Set<Long> existingRoles = userRoleMapper.findRoleIdsByUserId(userId);
Set<Long> conflicting = roleConflictMapper.findConflicts(newRoleId);
if (!Collections.disjoint(existingRoles, conflicting)) {
throw new BusinessException("Role duty conflict, cannot hold simultaneously");
}
userRoleMapper.insert(userId, newRoleId);
}Dynamic SoD:
/** Check at business execution (same process cannot have same person play two roles) */
public void approveOrder(Long orderId, Long userId) {
Order order = orderMapper.findById(orderId);
if (order.getCreatorId().equals(userId)) {
throw new BusinessException("Creator and approver cannot be the same person");
}
// Execute approval
}Static vs Dynamic SoD Difference:
Static SoD — Interception at role assignment; low flexibility (cannot hold conflicting roles simultaneously); simple implementation.
Dynamic SoD — Interception at business execution; high flexibility (can hold, but not in same process); complex implementation.
7.4 RBAC3: RBAC1 + RBAC2
Supports both inheritance and constraints simultaneously. Real-world enterprise RBAC is essentially RBAC3.
7.5 RBAC Limitations
RBAC naturally expresses "can/cannot" but falls short for:
View only own department data — RBAC cannot express; permission point lacks "department" dimension.
View only self-created — RBAC cannot express; permission point lacks "owner" dimension.
Access only during work hours — RBAC cannot express; permission point lacks "time" dimension.
View only clearance-level and above — RBAC cannot express; permission point lacks "classification" dimension.
These "conditional permissions" require ABAC.
Core 3: ABAC Attribute-Based Access Control Deep Dive
8.1 ABAC's Four Attribute Categories
Subject Attributes — Department, rank, user group, clearance level.
Object Attributes — Resource owning department, classification, owner, creation time.
Action Attributes — Read, write, delete.
Environment Attributes — Current time, IP, device, geo-location.
Decision logic: Subject attributes × Object attributes × Environment attributes → Allow/Deny.
Allow = rule(Subject.dept == Object.dept)
AND rule(Environment.time ∈ work_hours)
AND rule(Subject.clearance >= Object.classification)8.2 Typical ABAC Scenarios
View only own department data → Subject.dept == Object.dept
View only self-created → Subject.uid == Object.creator
Access only during work hours → Environment.time ∈ 9:00-18:00
View only clearance-level and above → Subject.clearance >= Object.level
Specific IP subnet only → Environment.ip ∈ internal_subnet
Non-work hours require MFA → Environment.time ∈ non_work_hours AND Subject.MFA_passed
8.3 ABAC Implementation Approaches
Annotation + AOP — @DataScope annotation + interceptor injects conditions; simple, suits data-level permissions.
Rule Engine — Drools/Aviator expressions; flexible, rules configurable.
Policy Engine — OPA/Cedar unified decision; centralized management, suits complex compliance.
Most systems only need the first approach (annotation + AOP); complex scenarios graduate to rule/policy engines.
8.4 Data-Level Permission Implementation
ABAC's most common landing is data-level permissions — same order:view permission, different people see different data ranges.
Data scope definition:
public enum Scope {
ALL, // All data
DEPT, // Own department
DEPT_AND_CHILD, // Own department and sub-departments
SELF // Only self
}Annotation definition:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataScope {
Scope value() default Scope.SELF;
String deptField() default "dept_id";
String creatorField() default "create_by";
}AOP Aspect:
@Aspect
@Component
public class DataScopeAspect {
@Around("@annotation(dataScope)")
public Object apply(ProceedingJoinPoint pjp, DataScope dataScope) throws Throwable {
SessionInfo user = UserContext.get();
// Pass data scope condition to MyBatis interceptor via ThreadLocal
DataScopeContext.set(buildCondition(user, dataScope));
try {
return pjp.proceed();
} finally {
DataScopeContext.clear();
}
}
private String buildCondition(SessionInfo user, DataScope scope) {
return switch (scope.value()) {
case ALL -> null; // No condition
case SELF -> scope.creatorField() + " = " + user.getUid();
case DEPT -> scope.deptField() + " = " + user.getDeptId();
case DEPT_AND_CHILD -> scope.deptField() + " IN (" + getDeptAndChildIds(user.getDeptId()) + ")";
};
}
private String getDeptAndChildIds(Long deptId) {
// Query own department and all child department IDs (department tree)
List<Long> idsList = deptMapper.findChildIds(deptId);
return idList.stream().map(String::valueOf).collect(Collectors.joining(","));
}
}MyBatis Interceptor Auto-Injection:
@Intercepts(@Signature(type = StatementHandler.class, method = "prepare",
args = {Connection.class, Integer.class}))
public class DataScopeInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
String condition = DataScopeContext.get();
if (condition == null) {
return invocation.proceed(); // No data scope restriction
}
// Intercept original SQL, append data scope condition after WHERE
StatementHandler handler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = handler.getBoundSql();
String originalSql = boundSql.getSql();
String newSql = injectCondition(originalSql, condition);
// Replace original SQL via reflection
Field field = boundSql.getClass().getDeclaredField("sql");
field.setAccessible(true);
field.set(boundSql, newSql);
return invocation.proceed();
}
private String injectCondition(String sql, String condition) {
// Simplified: append condition after WHERE (real impl should parse SQL AST)
if (sql.toUpperCase().contains("WHERE")) {
return sql + " AND " + condition;
}
return sql + " WHERE " + condition;
}
}Business interface only needs annotation:
@DataScope(value = Scope.DEPT)
@GetMapping("/order/list")
public List<Order> list() {
return orderMapper.selectAll(); // SQL auto-adds "where dept_id = #{user.deptId}"
}This achieves "same interface, different people see different data ranges" — RBAC governs "can you call this API," ABAC governs "which data can you see."
Note: Production SQL rewriting cannot use simple string concatenation (breaks complex SQL); should use JSqlParser or similar SQL parsing library to parse AST then inject conditions. The simplified code above only demonstrates the principle.
To be continued…
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.
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.
