Skip to content
RBAC vs ABAC vs PBAC: Which Permission Model Fits Your Compliance Needs?

RBAC vs ABAC vs PBAC: Which Permission Model Fits Your Compliance Needs?

This article compares ACL, RBAC, ABAC, and PBAC permission models through 12 interview questions covering role inheritance, separation of duties, data-level permissions, multi-tenant isolation, caching strategies, and when to adopt a policy engine for complex compliance.

CodeSmart Hoops
CodeSmart Hoops
CodeSmart Hoops

Interview Self-Test Questions

The article presents 12 interview questions mapped to sections of the companion piece "Permission Models and RBAC-ABAC Complete Analysis". Each question targets a core authorization concept.

Q1 : ACL vs RBAC difference? Why RBAC suits enterprise systems? (Sections II, VI)

Q2 : What are RBAC0/1/2/3? What problem does role inheritance solve? (Section VII)

Q3 : What is Separation of Duties (SoD)? Static vs dynamic SoD difference? (Section 7.3)

Q4 : What scenarios RBAC cannot express that require ABAC? Give three examples. (Section VIII)

Q5 : How to implement data-level permissions? Principle of same interface showing different data to different users? (Section 8.4)

Q6 : Why both frontend button-level and backend API-level permissions? Is frontend-only enough? (Section X)

Q7 : How to cache permissions? How to invalidate when role permissions change? What is the versioning mechanism? (Sections 9.5, 14.3)

Q8 : Multi-tenant SaaS permission isolation schemes? Most common bug in shared-table approach? What to return for cross-tenant access? (Section XI)

Q9 : Why can't "create" and "audit" roles be held by same person? Which RBAC layer? (Section 7.3)

Q10 : Why adopt PBAC policy engine for complex compliance? Relationship with RBAC/ABAC? (Section XII)

Q11 : Why use "module:resource:action" three-segment permission coding? Benefits? (Section 9.2)

Q12 : Performance issues when bulk-clearing cache on role permission change? How to optimize? (Section 14.3)

Reference Answers

Q1: ACL vs RBAC — Why RBAC Fits Enterprise Systems

Comparison:

Perspective : ACL is resource-centric (each resource lists who can access); RBAC is user-centric (user holds roles, roles map to permissions)

Association : ACL links user directly to resource; RBAC uses three-layer: User — Role — Permission

Maintenance : ACL requires per-resource adjustment on personnel changes; RBAC changing role automatically adjusts permissions

Best for : ACL suits few, relatively fixed resources (file systems); RBAC suits many users, relatively fixed roles (enterprise systems)

Four reasons RBAC suits enterprises:

Frequent personnel changes (onboarding, transfers, offboarding) but positions (roles) are stable — RBAC confines changes to user-role links without touching roles themselves.

Enterprises divide responsibilities by position; RBAC's "role" naturally maps to positions.

Bulk management efficiency: adding a permission for all operators means updating the "operator" role once; ACL would require per-user updates.

ACL maintenance explodes when both users and resources are numerous, becoming uncontrollable.

ACL still fits: file systems, cloud IAM, object storage — scenarios with few resources needing per-resource granularity.

Q2: RBAC0/1/2/3 and Role Inheritance

Levels:

RBAC0 : User-Role-Permission baseline three layers — solves basic authorization

RBAC1 : Role inheritance (parent_id) — solves duplicate role permission definitions

RBAC2 : Role constraints (Separation of Duties, etc.) — solves inability to express mutual exclusion / SoD

RBAC3 : RBAC1 + RBAC2 combined — complete enterprise-grade model

Role inheritance solves: "Operations Lead" and "Operations Specialist" share most permissions — Lead includes all Specialist permissions plus management ones. Without inheritance, Specialist permissions must be duplicated; with inheritance, Lead inherits Specialist and only defines its own additions.

Implementation: Add parent_id to role table; when loading permissions, recursively merge parent role permissions.

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;
}

Caveats: avoid cycles (A inherits B, B inherits A) — check before assignment; most systems support only single inheritance; keep inheritance chains shallow to ease permission tracing.

Q3: Separation of Duties (SoD) — Static vs Dynamic

Separation of Duties: split a complete process into multiple steps performed by different roles to prevent single-person fraud. Classic example: finance "create" and "audit" cannot be same person — self-create-self-approve is high fraud risk.

Static vs Dynamic SoD:

Static SoD : interception at role assignment; rule: same person cannot hold mutually exclusive roles simultaneously; low flexibility, simple implementation

Dynamic SoD : interception at business execution; rule: same person may hold both roles but cannot act as both in the same business process; high flexibility, complex implementation

Static SoD: user already has "create" role; assigning "audit" role is rejected immediately. Strong constraint but low flexibility — small companies needing dual-hatting are blocked.

Dynamic SoD: user may hold both roles, but execution checks "creator and auditor of the same order cannot be the same person". Flexible, suits understaffed scenarios.

Other RBAC2 constraints: cardinality (max N roles per user), prerequisites (must hold role A before role B).

public void assignRole(Long userId, Long newRoleId) {
    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);
}
public void approveOrder(Long orderId, Long userId) {
    Order order = orderMapper.findById(orderId);
    if (order.getCreatorId().equals(userId)) {
        throw new BusinessException("Creator and auditor cannot be the same person");
    }
    // execute approval
}

Q4: When RBAC Falls Short — Three ABAC Scenarios

RBAC naturally expresses "can this interface be called" but cannot express conditional permissions — same permission point allowed under different conditions, or same interface returning different data per user.

View only own department data: order:view means "can view orders", but "only view orders belonging to own department" requires comparing subject attribute (department) with object attribute (order's owning department).

View only self-created: order:view cannot express "only view orders I created"; requires comparing subject ID with object creator field.

Access only during business hours: order:view cannot express "only accessible 9–18"; requires environment attribute (current time).

ABAC's four attribute types:

Subject attributes: department, rank, clearance level

Object attributes: owning department, classification, owner

Action attributes: read / write / delete

Environment attributes: time, IP, device, geo-location

Decision logic: Subject × Object × Environment → Allow/Deny.

Relationship: ABAC does not replace RBAC; it supplements — RBAC governs coarse-grained "can call interface", ABAC governs fine-grained "which data visible / under what conditions". Most systems need only RBAC + ABAC for data-level permissions.

Q5: Data-Level Permission Implementation

Data-level permission: same order:view permission, different users see different scopes — all, own department, department + children, self only.

Implementation principle (Annotation + MyBatis Interceptor):

Define data scope enum: ALL / DEPT / DEPT_AND_CHILD / SELF

Annotate interface: @DataScope(value = Scope.DEPT) AOP aspect: intercept annotation, build SQL condition based on current user and scope (e.g., dept_id = #{user.deptId}), store in ThreadLocal

MyBatis interceptor: intercept SQL execution, retrieve condition from ThreadLocal, auto-append to original SQL's WHERE clause

@Aspect
@Component
public class DataScopeAspect {
    @Around("@annotation(dataScope)")
    public Object apply(ProceedingJoinPoint pjp, DataScope dataScope) throws Throwable {
        SessionInfo user = UserContext.get();
        String condition = switch (dataScope.value()) {
            case ALL -> null;
            case SELF -> "create_by = " + user.getUid();
            case DEPT -> "dept_id = " + user.getDeptId();
            // ...
        };
        DataScopeContext.set(condition); // pass to MyBatis interceptor
        return pjp.proceed();
    }
}

Business interface remains unaware:

@DataScope(value = Scope.DEPT)
@GetMapping("/order/list")
public List<Order> list() {
    return orderMapper.selectAll(); // SQL auto-appends "where dept_id = #{user.deptId}"
}

Production caution: SQL rewriting must not use naive string concatenation (breaks complex SQL); use JSqlParser or similar to parse AST and inject conditions safely, avoiding SQL injection and syntax breakage.

Q6: Frontend Button-Level + Backend API-Level Permissions

Frontend-only is insufficient. Frontend button hiding is merely UX optimization — prevents users from seeing/clicking unauthorized buttons. But frontend checks are bypassable:

Attackers craft requests directly via proxy tools, bypassing buttons.

Attackers tamper frontend JS to restore hidden buttons.

Attackers call APIs directly with curl.

Backend API validation is the last line of defense and must independently verify. Even if frontend is bypassed, backend rejects unauthorized requests.

@RequiresPermission("user:delete")
@DeleteMapping("/user/{id}")
public void delete(@PathVariable Long id) { ... }

Iron rules:

Frontend permissions control "visibility" (user experience)

Backend permissions control "security" (privilege escalation prevention)

Both required, backend is authoritative

Real incident: a system only hid "delete" button frontend; backend API had no check. Attacker discovered callable API and bulk-deleted competitor data. Frontend hiding was useless.

Q7: Permission Caching, Invalidation, and Versioning

Permission caching: loaded user permissions stored in Redis, key like perm:user:{userId}, TTL 1 hour. Avoids querying 5 tables per request.

Invalidation scenarios:

User role change → clear that user's cache

Role permission change → clear cache of ALL users holding that role

User login/logout → reload

Most commonly missed: when role permissions change, cannot clear just one user — must find all users with that role and invalidate all. Forgetting this causes permission changes to not take effect (revoked permission still usable) — a frequent bug.

Versioning mechanism (optimizes bulk invalidation): role carries version; cache key includes version: perm:user:{uid}:{roleVersion}. On role permission change, global role version +1; old cache keys naturally miss (no longer matched), no per-key deletion needed.

public Set<String> loadPermissions(Long userId) {
    Long roleVersion = roleVersionService.getVersion();
    String key = "perm:user:" + userId + ":" + roleVersion; // cache key includes version; role change bumps version, old cache auto-expires
    // ...
}

Advantage: change only increments one version number; avoids deleting 100k user cache keys, eliminating Redis pressure spikes.

Other optimizations: async cleanup via message queue; short TTL (5 min) tolerating brief inconsistency.

Q8: Multi-Tenant SaaS Permission Isolation

Three isolation schemes:

Separate databases: one DB per tenant — strongest isolation, highest cost, for large customers, strict compliance

Shared DB, separate schemas: one schema per tenant — medium isolation, medium cost, for mid-size tenants

Shared table + tenant_id: all data tagged with tenant_id — weak (code-enforced), lowest cost, for small tenants, high volume

Most common bug in shared-table scheme — tenant data leakage: query omits tenant_id condition, allowing Tenant A to read Tenant B's data. This is the most severe SaaS security incident.

Defenses:

Use MyBatis interceptor to auto-inject tenant_id; business code never writes it manually.

Critical interface test: Tenant A's token accessing Tenant B's resource ID must return 404.

Regular code scans to ensure no raw SQL missing tenant_id.

Cross-tenant must return 404, not 403:

403 (forbidden) leaks "resource exists but no access" — attacker can enumerate valid resource IDs.

404 (not found) leaks nothing — attacker cannot distinguish "no access" from "does not exist".

Super-admin special handling: cross-tenant ops go through separate "platform admin console" (physically isolated from tenant console), interfaces explicitly annotated @IgnoreTenant to bypass isolation, fully audited.

Q9: Why "Create" and "Audit" Roles Cannot Be Same Person — RBAC2

Reason: in finance, create (draft document) and audit (approve document) by same person enables self-create-self-approve, extreme fraud risk. SoD splits a process into steps done by different roles for mutual checks.

Belongs to RBAC2 (role constraints): RBAC2 adds role constraints on top of RBAC0; most common is SoD, in two flavors:

Static SoD: blocks at role assignment — user with "create" role cannot be granted "audit" role. Strong but inflexible — small teams needing dual-hatting are blocked.

Dynamic SoD: blocks at execution — user may hold both roles, but same order's creator and auditor cannot be same person. Flexible, suits understaffed scenarios.

Implementation code shown in Q3.

Q10: Why Adopt PBAC Policy Engine for Complex Compliance? Relation to RBAC/ABAC

Pain points driving PBAC adoption:

Extremely complex rules: time, location, classification, approval flow, context combinations

Rules scattered everywhere: annotations + code + config; hard to maintain and audit

Frequent rule changes: rule change requires full redeployment

Multi-system permission unification: each system has inconsistent rules

PBAC (Policy-Based Access Control) centralizes permission rules into a standalone policy engine (OPA, Cedar, Drools); business systems call the engine for decisions. Rules decoupled from business code; rule changes without redeployment; centralized audit.

Relation to RBAC/ABAC: PBAC does not replace RBAC/ABAC; it uses a policy engine to host these models — policies can encode RBAC rules (role permissions), ABAC rules (attribute checks), and compliance rules (approval flows). Simply put, PBAC is a "unified container" for RBAC + ABAC + compliance rules.

Policy example (OPA Rego):

allow {
  input.action == "view"
  input.resource.type == "order"
  input.subject.dept == input.resource.dept  # ABAC: same department
}

allow {
  input.environment.hour >= 9  # environment attribute: business hours
  input.environment.hour <= 18
}

When to adopt PBAC:

Simple back-office → annotations + AOP sufficient, no PBAC.

Medium + data-level → RBAC + ABAC annotations sufficient, no PBAC.

Complex compliance, multi-system unification, fintech/gov audit strict → adopt PBAC.

Key insight: PBAC is heavyweight; using it for simple systems is over-engineering. Only adopt when rules are complex enough to be scattered and unmaintainable.

Q11: Why "Module:Resource:Action" Three-Segment Permission Coding?

Three-segment format: module:resource:action, e.g., user:delete, order:approve, finance:report.

Readability: user:delete instantly means "delete user"; clearer than numeric IDs or arbitrary names.

Wildcard matching: user:* means "all user operations"; enables module-level bulk grants or audits.

Module-based assignment: when granting permissions, filter by module — "give operations role all order permissions" is obvious.

Frontend-backend unity: frontend buttons, backend APIs, menus all share same coding; enables cross-referencing and dynamic rendering.

Collision avoidance: permissions from different modules never clash.

Anti-patterns: numeric IDs ( perm_id=1) — meaningless, require table lookup; arbitrary names ( canDelete, isAdmin) — inconsistent, hard to extend, hard to manage by module.

Practice: manage codes in sys_permission table; interface annotations reference codes; add permission point when adding interface to avoid "interface exists but no permission point"; never change live codes (breaks all references) — if change needed, add compatibility mapping.

Q12: Bulk Cache Clear Performance Issues and Optimizations

Performance problem: role permission change triggers clearing cache of all users holding that role. If 100k users hold the role, one change issues 100k Redis DEL commands — instant Redis pressure spike, possible brief stalls affecting other services.

Optimization approaches:

1. Versioning (recommended): role has version; cache key includes version: perm:user:{uid}:{roleVersion}. Role change increments global version; old keys naturally miss (expire via TTL), zero bulk deletion.

public Set<String> loadPermissions(Long userId) {
    Long roleVersion = roleVersionService.getVersion();
    String key = "perm:user:" + userId + ":" + roleVersion;
    // ...
}

Advantage: change touches only one version number; no bulk delete; zero pressure.

2. Message queue async clear: split bulk clear into MQ messages; multiple consumers process asynchronously; avoids synchronous blocking and concentrated Redis pressure.

3. Short TTL: set TTL low (e.g., 5 min); tolerate brief inconsistency — permission change takes effect within 5 min; avoids active clear complexity. Suits low real-time requirement scenarios.

4. Batched clear: split 100k users into batches (1k each), clear with intervals; avoids instantaneous pressure.

Selection guide:

High real-time + large user base → versioning.

Medium real-time → short TTL + async clear on role change.

Simple systems → direct clear; volume small, no pressure.

Key insight: cache invalidation isn't just "clear or not"; it's "how to clear without overwhelming Redis". Versioning uses "don't actively clear; let key change cause natural expiry" — a standard technique for large-scale systems.

References

Permission Models and RBAC-ABAC Complete Analysis — companion source for this self-test

NIST RBAC Standard (INCITS 359-2004) — RBAC four-layer model definition

OWASP Access Control Cheat Sheet — access control best practices

Spring Security Complete Analysis — Spring Security permission implementation

Sa-Token Authentication Framework Complete Analysis — Sa-Token permission validation

Authentication & Authorization Architecture Selection Complete Analysis — authN/authZ layering

OPA (Open Policy Agent) / Cedar / Drools — policy engines

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Interview questionsMulti-tenancyRBACACLABACPBACdata-level permissionsPermission cachingPermission codingSeparation of Duties
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.