Skip to article content
FrontendXLesson 21 / 24

Authorization, RBAC and multi-tenancy

Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.

advanced · about 55 minutes · 2 exercises

  • Explain
  • Debug

What you will be able to do

#
  • Enforce ownership and role checks on every resource access.
  • Prevent insecure direct object references (IDOR).
  • Isolate tenants so one tenant cannot read another's rows.

Overview

#

Authentication says who you are; authorization says what you may do. Every read and write must check both the role and the ownership or tenant of the target resource.

IDOR

If a handler fetches by id alone, a user can change the id and read someone else's data.

snippet.js
// vulnerable: any authenticated user can read any invoice
const invoice = await db.query('SELECT * FROM invoices WHERE id = $1', [id]);

// safe: scope the query to the caller's tenant
const invoice = await db.query(
  'SELECT * FROM invoices WHERE id = $1 AND tenant_id = $2',
  [id, req.user.tenantId]
);

RBAC

Roles map to permissions. Check the permission the action requires, not the role name, so adding a role does not require editing every handler.

snippet.js
function requirePermission(permission) {
  return (req, res, next) => {
    if (!req.user.permissions.includes(permission)) {
      return res.status(403).json({ error: { code: 'forbidden' } });
    }
    next();
  };
}

Tenant isolation

Put the tenant id in every query, or use row-level security in the database so a missing filter cannot leak data. Defense in depth: enforce in the query and in the database.

Common pitfalls

  • Checking the role but not ownership, so any user can edit any record.
  • Trusting a tenant id from the request body instead of the authenticated session.
  • Returning 404 for a resource that exists but is not yours only sometimes, creating an enumeration oracle.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Debug

    This endpoint lets any logged-in user read any invoice. Fix the IDOR.

    starter.javascript
    app.get('/invoices/:id', requireAuth, async (req, res) => {
      const invoice = await db.query('SELECT * FROM invoices WHERE id = $1', [req.params.id]);
      res.json(invoice.rows[0]);
    });

    Reveal the reference answer
    reference.javascript
    app.get('/invoices/:id', requireAuth, async (req, res) => {
      const invoice = await db.query(
        'SELECT * FROM invoices WHERE id = $1 AND tenant_id = $2',
        [req.params.id, req.user.tenantId]
      );
      if (!invoice.rows[0]) return res.status(404).json({ error: { code: 'not_found' } });
      res.json(invoice.rows[0]);
    });

    Authored expected output: The query is scoped to the caller's tenant, so another tenant's invoice returns 404.

    Adding tenant_id from the authenticated session to the WHERE clause prevents reading across tenants even if the id is guessed.

  2. Exercise 2Explain

    Why is checking permissions better than checking a role name in each handler?

    starter.text
    if (req.user.role === 'admin') { ... }
    

    Reveal the reference answer
    reference.text
    A permission check expresses the capability the action needs, so adding a new role that also has that capability requires no handler changes. Role-name checks scatter role knowledge across the codebase and break when roles are added or renamed.

    Authored expected output: Explains decoupling handlers from role names by checking capabilities.

    Permission-based checks are more stable and testable than role-name checks.

Common misconceptions

#
  • A hidden id is authorization: obscurity is not access control, and ids are guessable.
  • Checking authorization once at login is enough: every resource access needs its own check.

Follow-up practice

#
  • backend-databases-caching

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.