Web Security 11 🛡️ Broken Access Control & Authorization — Preventing IDOR/BOLA, enforcing RBAC/ABAC, and securing multi-tenant boundaries
Access control is the gatekeeper of your application. While authentication determines who a user is, authorization determines what they are allowed to do. Broken Access Control remains the number one risk on the OWASP Top 10 because it is often a logical flaw rather than a syntactic one. When a developer forgets to verify that a logged-in user actually owns the record they are accessing, they expose the system to unauthorized data access, modification, or destruction.
Modern web architectures—with their complex requirements for multi-tenancy, granular roles, and dynamic permissions—make authorization logic brittle. This chapter covers the spectrum of authorization vulnerabilities, from the simple IDOR (Insecure Direct Object Reference) to the complexities of implementing robust Role-Based and Attribute-Based Access Control systems. We will explore how to architect authorization into the core of your backend, rather than treating it as an afterthought.
Key point: The fundamental rule of secure authorization is that the server must verify the user’s relationship to the requested object on every single request; you cannot rely on the client to enforce rules or assume that a valid session token grants access to all data.
Why exists
The “Client-Side Trust” problem.
Developers often hide UI elements (like an “Edit” button) for unauthorized users, assuming this secures the underlying API endpoint. However, attackers do not use your UI; they use tools like curl or Postman. Authorization must happen on the server, not the client.
The IDOR/BOLA ambiguity.
IDOR (Insecure Direct Object Reference) and BOLA (Broken Object Level Authorization) are essentially the same flaw: exposing an internal object identifier (like a database ID) and failing to check if the user is authorized to interact with that specific ID. It exists because mapping requests directly to database lookups is easy, but verifying ownership is “expensive” in terms of code complexity.
The complexity of multi-tenancy.
In SaaS applications, two users might both be “Admins,” but they belong to different companies (tenants). If your authorization logic only checks user.role == 'admin' and ignores user.tenant_id, you have a massive data leak. Authorization must be context-aware.
The scalability of permissions.
As applications grow, “Admin” vs “User” roles become insufficient. You may need permissions based on time of day, subscription level, or resource ownership. This drives the need for move from simple roles to dynamic attribute-based checks.
The auditability requirement.
Authorization systems exist to provide a trail of intent. When access is broken, you lose the ability to answer “who did what and why?” Robust access control frameworks provide centralized logging, making it easier to detect anomalous behavior and potential breaches.
a. IDOR/BOLA: The Ownership Check
IDOR occurs when an application exposes a reference to an internal implementation object—like a database key—without an authorization check. If a user can change /api/users/100 to /api/users/101 and access another person’s private profile, the system is vulnerable. The fix is never to assume that if a user provides an ID, they are authorized to see it.
// VULNERABLE: Trusting the user-provided ID
app.get('/api/orders/:orderId', (req, res) => {
const order = db.orders.findById(req.params.orderId);
res.json(order); // Returns any order if ID exists
});
To fix this, you must introduce the “Ownership Check.” You retrieve the resource and verify that the resource’s owner matches the user_id stored in the secure session (JWT or Cookie), not the user-provided input.
// SECURE: Verifying ownership against the session
app.get('/api/orders/:orderId', (req, res) => {
const order = db.orders.findById(req.params.orderId);
if (order.userId !== req.session.userId) {
return res.status(403).send('Forbidden');
}
res.json(order);
});
b. RBAC vs. ABAC: Architectural Choices
Role-Based Access Control (RBAC) assigns permissions to roles (Admin, Editor, Viewer). It is simple to implement but becomes unmanageable as the number of roles grows. Attribute-Based Access Control (ABAC) is more granular. It evaluates requests based on attributes of the user (e.g., department), the resource (e.g., classification), and the environment (e.g., access_time).
// RBAC Check
function canEdit(user) {
return user.roles.includes('EDITOR');
}
// ABAC Check
function canEdit(user, resource) {
return (user.department === resource.department) &&
(resource.status === 'DRAFT') &&
(user.clearance >= resource.requiredClearance);
}
RBAC is sufficient for smaller applications, but ABAC is the gold standard for large, complex enterprise systems. You don’t need to choose just one; many systems use a hybrid approach where roles define high-level access, and attributes perform fine-grained filtering.
c. Multi-tenant Boundaries
In multi-tenant applications, data isolation is critical. You must ensure that “Tenant A” can never query data from “Tenant B.” The safest way to enforce this is to include the tenant_id in every single database query and every authorization check.
// SECURE: Enforcing tenant isolation at the query level
app.get('/api/projects/:id', (req, res) => {
const project = db.projects.findOne({
where: {
id: req.params.id,
tenantId: req.session.tenantId // Mandatory scope
}
});
if (!project) return res.status(404).send('Not Found');
res.json(project);
});
If you ever forget to add the tenantId filter, you create a potential cross-tenant leak. The best practice is to implement a middleware that injects the tenantId context into your database client or ORM, ensuring all queries are automatically scoped to the current user’s tenant by default.
Complete Example Session
// ============================================
// PART 1: THE VULNERABLE APPROACH
// ============================================
// Just getting ID from URL
app.get('/api/files/:fileId', (req, res) => {
const file = db.files.get(req.params.fileId);
res.json(file);
});
// ============================================
// PART 2: THE SECURE APPROACH (IDOR PROTECTION)
// ============================================
app.get('/api/files/:fileId', (req, res) => {
// 1. Fetch
const file = db.files.get(req.params.fileId);
// 2. Validate session context
if (file.ownerId !== req.user.id) {
return res.status(403).send('Unauthorized');
}
res.json(file);
});
// ============================================
// PART 3: MULTI-TENANT SCOPING
// ============================================
// Middleware forces tenant context
const tenantMiddleware = (req, res, next) => {
req.tenantId = req.session.tenantId;
next();
};
app.get('/api/files/:fileId', tenantMiddleware, (req, res) => {
// Query includes tenantId + fileId
const file = db.files.findOne({
id: req.params.fileId,
tenantId: req.tenantId
});
// ...
});
This sequence demonstrates the progression from a vulnerable, trusting implementation to a secure, scoped implementation that validates both user ownership and tenant boundaries.
Quick Reference
Authorization Models
| Model | Basis | Use Case |
|---|---|---|
| RBAC | User Roles | Basic apps, internal tools |
| ABAC | Attributes/Policies | Complex compliance, enterprise |
| ACL | Access Control Lists | Filesystems, granular objects |
Multi-tenancy Strategies
| Strategy | Implementation | Risk |
|---|---|---|
| Logical | WHERE tenant_id = ? | High (Developer error) |
| Database | Different Schema/DB | Low (Strong isolation) |
| Row Level | RLS (Postgres) | Medium (DB specific) |
Vulnerability Prevention
| Threat | Prevention |
|---|---|
| IDOR | Validate object ownership in DB |
| BOLA | Validate resource access by user context |
| Broken RBAC | Centralize auth checks in middleware |
Best Practices
✅ Do This:
// Validate every access check on the server
if (record.tenantId !== user.tenantId) throw Error(); // ✅
// Use UUIDs to prevent ID guessing
// (e.g., a8c3-4f91-...) // ✅
// Centralize authorization logic
const canAccess = authService.canAccess(user, 'read', res); // ✅
// Use Row Level Security (RLS) in databases
// (e.g., Postgres RLS policies) // ✅
❌ Don’t Do This:
// Trust the client to hide buttons
// (API is still reachable) // ❌
// Use sequential IDs (1, 2, 3...)
// (Easily enumerable by attackers) // ❌
// Check authorization only in one spot
// (Missed checks lead to holes) // ❌
// Store roles/permissions in the client
// (Easily tampered with) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Enumerable IDs | Using serial integers | Switch to UUIDs / CUIDs |
| Client-Side Logic | Devs treat UI as security | Move all authz to server |
| Tenant Leak | Forgetting tenant_id scope | Use global DB middleware |
| Over-privileged Roles | “Admin” has too much power | Implement fine-grained ABAC |
Real-World Examples
1. Checking File Access
const doc = await db.docs.find(id);
if (doc.creatorId !== userId) return error();
2. Tenant Scoped Query
db.items.findMany({ where: { tenantId } });
3. Role Middleware
const authorize = (role) => (req, res, next) => {
if (req.user.role !== role) return forbidden();
next();
};
4. Using UUIDs
// '550e8400-e29b-41d4-a716-446655440000'
5. Attribute Check
if (user.subscription === 'premium' && resource.tier === 'basic') return ok();
6. Database RLS
CREATE POLICY tenant_isolation ON files USING (tenant_id = current_user_tenant());
7. Session Validation
const session = await getSession(req);
if (!session.active) return unauthorized();
8. Resource Level Auth
const hasAccess = await acl.check(user, 'edit', resource);
9. Audit Logging
log('Access Denied', { user, resource, time });
10. URL Parameter Sanitization
const id = sanitize(req.params.id); // validate uuid format
Visual
The IDOR Vulnerability Flow
┌──────────────────────────────────────────────┐
│ ATTACKER │
│ GET /api/orders/999 (Mine) │
│ │ │
│ GET /api/orders/1000 (Victim's) │
│ │ │
│ SERVER (Vulnerable) │
│ db.orders.findById(1000) ──► Returns Data │
│ │ │
│ ATTACKER │
│ Reads Victim's Data │
└──────────────────────────────────────────────┘
RBAC vs ABAC Decision Logic
┌──────────────────────────────────────────────┐
│ REQUEST ──► AUTHORIZATION ENGINE │
│ │
│ RBAC: │
│ User has "Admin"? ──► YES │
│ │
│ ABAC: │
│ User has "Admin"? ──► YES │
│ Resource is "Public"? ──► YES │
│ Time is "Business Hours"? ──► YES │
│ RESULT ──► ALLOW │
└──────────────────────────────────────────────┘
Multi-Tenant Isolation
┌──────────────────────────────────────────────┐
│ DATABASE (All Data) │
│ ┌──────────────────────┐ │
│ │ Tenant A Data │ │
│ │ [Record 1] │ │
│ └──────────────────────┘ │
│ ┌──────────────────────┐ │
│ │ Tenant B Data │ │
│ │ [Record 2] │ │
│ └──────────────────────┘ │
│ │
│ QUERY: WHERE tenant_id = 'B' │
│ RESULT: [Record 2] (Only) │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Vulnerability | Broken Access Control |
| Key Prevention | Server-side validation |
| ID Strategy | UUIDs |
| Tenant Strategy | Scoped filtering |
| Model | RBAC/ABAC |
Key takeaways:
- Authorization is server-side only. Client-side UI restrictions are for UX, not security; the API must re-verify ownership for every single request.
- Enforce multi-tenant boundaries. Always scope database queries by
tenant_idto prevent cross-tenant data leaks. - Avoid enumerable IDs. Replace sequential integer IDs (1, 2, 3) with UUIDs to make it significantly harder for attackers to guess or enumerate resources.
- RBAC vs. ABAC. Start with RBAC for simplicity, but adopt ABAC (Attribute-Based Access Control) when you need fine-grained, policy-driven security.
- Centralize authorization. Do not scatter
ifstatements throughout your controllers. Use middleware or dedicated authorization services to keep logic consistent.
Remember: Broken Access Control is a failure of logic, not syntax. You must assume that any user can attempt to access any resource. By building your system to verify ownership and tenant isolation at the database level, you create a defensive depth that protects your application even when individual endpoints are compromised.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!