Skip to article content
LESSON 19 / 28

Authorization and tenant isolation

Enforce who may access each resource at the data boundary, including direct requests and cached responses.

What you will be able to do

  • Separate route visibility from resource permissions.
  • Scope reads and writes by authenticated tenant and owner.
  • Minimize returned data and protect server-only dependencies.
  • Explain proxy, CSRF, XSS and rate-limit responsibilities.

Ask about the record, not just the route

A signed-in user may still be forbidden from reading a particular invoice. Authorization combines the verified actor, the requested action and the target resource. The server must obtain the actor from its session and load enough trusted resource metadata to decide. A client-supplied role, owner ID or organization name is an input to validate, not evidence of permission.

Start with a permission table: members can read their own records, managers can read records in their tenant, and archived records cannot be edited. Clarify whether an admin is global or tenant-scoped. The word admin alone is dangerously ambiguous. A small explicit policy is easier to review than permissions scattered across components, handlers and database queries.

Constrain the data operation itself

An object ID may be guessable or copied from another tab. Fetching solely by that ID and checking only whether the user is logged in allows an insecure direct object reference. Include tenant identity and appropriate ownership in the query or a tightly controlled policy layer. A server action must perform the same checks even if only authorized users can see its button.

For writes, keep the authorization predicate in the update itself or use a transaction that prevents relevant state from changing between check and write. The example is a storage-adapter contract sketch. The database adapter, session lookup and response policy must be supplied by the actual application; returning a zero row count should not disclose another tenant's private record existence.

Shared application logic

lib/document-policy.ts
type Actor = { id: string; tenantId: string; role: "member" | "admin" };
type Document = { ownerId: string; tenantId: string; archived: boolean };
export function canEdit(actor: Actor, document: Document) {
  return actor.tenantId === document.tenantId && !document.archived &&
    (actor.role === "admin" || actor.id === document.ownerId);
}

Server execution

lib/document-write.ts
import "server-only";
export const renameOwnedDocumentSql = `
  UPDATE documents SET title = $1
  WHERE id = $2 AND tenant_id = $3 AND owner_id = $4
  RETURNING id, title
`;

PAUSE AND PREDICT

An admin from tenant A requests a record in tenant B. The policy says admins are tenant-scoped. What should happen?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Return the smallest safe data shape

A database row can include fields the browser should never receive: secret tokens, internal notes, billing flags or personal details unrelated to the screen. A DTO selects the necessary safe fields before serialization. Keeping a module server-only helps catch accidental imports, but a server-rendered component can still leak sensitive values by placing them in props, HTML or logs.

Apply the same reasoning to caches. A key must distinguish authorization-relevant identity when data varies by user or tenant. A shared cache entry named dashboard can become a data leak even when the database query was originally correct. Do not cache a permission decision longer than the product can tolerate changes, and invalidate or re-check it when membership is revoked.

Use request interception for the right job

Proxy can redirect obvious unauthenticated navigation and add headers, but it is not the complete security boundary. Matchers, alternative entry points and future refactors can bypass a route-level check. Slow authorization database work also makes request interception expensive. Keep authoritative data and mutation checks in server-only application code, close to the resource operation.

Distinguish CSRF from XSS when defending a design. CSRF abuses credential sending from a different origin; XSS executes attacker-controlled code within the application context. Cookie policy, origin validation and framework action protections address parts of the former. Safe rendering, strict handling of rich content and a considered content-security policy help with the latter. Neither replaces resource permissions.

PAUSE AND PREDICT

Proxy redirects unauthenticated page visits. Where must the edit action still enforce permission?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Prove a denial as deliberately as a success

Create two users in different tenants and try to read or mutate each other's IDs. Then repeat within one tenant for owner-only and admin operations. Test archived records, revoked membership and direct requests without visiting the page. Negative cases establish the boundary more convincingly than a screenshot of a hidden button.

Add operational protections based on the endpoint: rate limits, payload bounds, audit events and careful log redaction. In a multi-instance service, a local Map is not a shared rate limit. Record actor, action and permitted outcome without storing credentials or full sensitive payloads. The interview explanation should name both the invariant and the concrete place where it is enforced.

A valid signature is not a current permission lookup

A signed token can truthfully assert that a user belonged to tenant A when the token was issued. If that membership is removed later, signature verification alone still succeeds until expiry. The server needs a clear freshness contract for authorization claims. For immediate enforcement, consult current membership or a checked policy/session version. For a bounded stale window, choose short-lived claims and make that limitation explicit.

Never accept a tenant or role merely because the browser copied it from a token or provider. The server verifies the credential itself, derives trusted identity and checks the target resource against the application policy. An HttpOnly cookie reduces direct token reading by page JavaScript, but it does not prevent a malicious script from making an authenticated same-origin request. The requested operation still needs permission checks.

A no-session-database design can keep basic identity verification stateless while using the resource database or an authorization service for current permissions. If there is no current authority anywhere, immediate detection of a revoked role is impossible from an unchanged signed token alone. Explain that information limit directly instead of promising free real-time revocation.

Misconceptions to replace

Compare the tempting shortcut with the model you can verify in code.

CLAIM TO CHALLENGEAn unguessable record ID is sufficient access control.
A more accurate model

The server must still check the verified actor, action and resource.

How to check it

Change a record ID in a direct request using a second test identity.

CLAIM TO CHALLENGEA valid signed role is necessarily current.
A more accurate model

Role claims can outlive the permission they describe; immediate revocation requires current state or authority.

How to check it

Authentication lesson expiry/rotation section and Next.js data-security guidance.

Mistakes to catch in your own code

  • Trusting a client role or tenant ID.
  • Using proxy as the only authorization layer.
  • Returning a whole ORM object to a Client Component.
  • Sharing user-specific cache entries under a global key.

Write it by hand

JavaScript logic playground

Apply a resource permission policy

Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.

  1. Input has actor or null, resource {ownerId,tenantId,archived}, and action read or edit.
  2. Deny anonymous callers and all cross-tenant access.
  3. Within a tenant, admin or owner may read; edit additionally requires archived=false.
  4. Return {allowed,reason}, using unauthenticated, tenant, role, archived or allowed in that priority order.

Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 4 test cases
  1. Owner can edit

    Input

    {
      "actor": {
        "id": "u1",
        "tenantId": "t1",
        "role": "member"
      },
      "resource": {
        "ownerId": "u1",
        "tenantId": "t1",
        "archived": false
      },
      "action": "edit"
    }

    Expected

    {
      "allowed": true,
      "reason": "allowed"
    }
  2. Admin remains tenant scoped

    Input

    {
      "actor": {
        "id": "a",
        "tenantId": "t2",
        "role": "admin"
      },
      "resource": {
        "ownerId": "u1",
        "tenantId": "t1",
        "archived": false
      },
      "action": "read"
    }

    Expected

    {
      "allowed": false,
      "reason": "tenant"
    }
  3. Archived write denied

    Input

    {
      "actor": {
        "id": "u1",
        "tenantId": "t1",
        "role": "member"
      },
      "resource": {
        "ownerId": "u1",
        "tenantId": "t1",
        "archived": true
      },
      "action": "edit"
    }

    Expected

    {
      "allowed": false,
      "reason": "archived"
    }
  4. Anonymous denied first

    Input

    {
      "actor": null,
      "resource": {
        "ownerId": "u1",
        "tenantId": "t1",
        "archived": false
      },
      "action": "read"
    }

    Expected

    {
      "allowed": false,
      "reason": "unauthenticated"
    }
Reveal the worked solution and reasoning
solution.js
function solve(input) {
  const a = input.actor;
  const r = input.resource;
  if (!a) return { allowed: false, reason: "unauthenticated" };
  if (a.tenantId !== r.tenantId) return { allowed: false, reason: "tenant" };
  if (a.role !== "admin" && a.id !== r.ownerId) return { allowed: false, reason: "role" };
  if (input.action === "edit" && r.archived) return { allowed: false, reason: "archived" };
  return { allowed: true, reason: "allowed" };
}

Rule order makes the result deterministic and reviewable.

A production endpoint may deliberately hide these internal denial reasons from the caller.

The policy assumes actor identity was already verified by trusted server code.

Verify it in a real Next.js application

Next.js application lab

Verify tenant, role and Origin checks at each entry point

Open the local application route /dashboard after starting the workbench. Follow the experiment and collect the evidence described below.

Make the change

  1. Use the existing practice identities: Ada is a North administrator, Linus a North member, and Grace a South administrator. Inspect requireUser, createTask, toggleTask, changePrice and the task Route Handler before sending requests.
  2. As Ada, GET and PATCH /api/tasks/south-1 and verify the non-disclosing 404 response. Repeat as Grace to access that South task. For PATCH, send the configured local Origin and a current version; an unrelated or missing Origin is rejected before the write.
  3. As Linus, inspect /cache and attempt the price mutation directly. The existing Server Action requires an administrator even when the UI control is bypassed. Task edits follow tenant membership; the fixture has no separate per-user task ownership model.
  4. Inspect proxy.ts: it adds response headers and does not authorize data. Confirm that the dashboard, actions and API obtain identity on the server and filter the target resource independently.
  5. Compare opaque and stateless sessions after a controlled role change in a separate fixture. The opaque path reads the current user record, while signed claims can stay stale for five minutes.
  6. Implementation extension: add a current permission lookup, policy version or revocation check for sensitive operations. Add per-user ownership only if the new requirements demand it, and test those additional denial cases.

Check the behavior

  • Anonymous task reads return 401; a user from another tenant receives 404 without the other tenant task being returned or changed.
  • A wrong or absent Origin produces 403 on the cookie-authenticated task PATCH endpoint. A valid Origin alone does not grant resource permission.
  • A member cannot change catalogue prices by calling the action directly; an authorized administrator can commit a valid versioned change.
  • The expected tenant policy is enforced in server reads and writes, independently of Proxy and hidden buttons.
  • Fresh role lookup for stateless sessions is an extension. Do not report the current signed-claim implementation as immediately reflecting demotion.
Review the application reasoning

The pure permission kata cannot establish coverage of the real entry points. Use both existing API denial tests and direct action experiments, and record which session model supplies the permission claims for each observation.

Open the project files and run instructions

A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.

The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.

Terminal
cd nextjs-interview-lab
npm ci
npm run dev

# In a second terminal
npm test

# Stop dev, then verify the production application
npm run build
npm start

# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2e

Open http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.

Explain it in an interview

Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.

  1. 01How would you find and fix an object-level authorization bug?

    I would submit a valid request with another user's record ID and verify the server response and stored result. If access succeeds, the missing invariant is permission on that specific object.

    I would scope the DAL query or mutation by authenticated identity and resource rules, then add negative tests across users and tenants. Hiding the record in the UI is not the fix.

    Follow-up questions

    • Should forbidden and absent records return different responses?
    • How do you avoid a check-then-write race?
  2. 02Why return a DTO instead of a complete database row?

    A DTO makes the browser-visible contract explicit and excludes fields that the screen does not need. This reduces accidental leakage through props, HTML and logs.

    I also validate external data at runtime. A TypeScript type documents a shape, but it does not remove extra fields from an object or establish that the object is safe to serialize.

    Follow-up questions

    • Which fields would you remove from a user row?
    • Can a Server Component still leak secrets?
  3. 03Why not centralize all authorization in proxy.ts?

    Proxy handles request interception and can make optimistic redirects. It does not replace authorization for every action, handler and underlying resource.

    I keep permission logic reusable in the server DAL so alternative entry points enforce the same rule. A matcher change should not silently remove access control.

    Follow-up questions

    • What should a webhook verify?
    • Where should a slow membership lookup run?
  4. 04How can caching introduce a cross-tenant leak?

    If a result that varies by tenant is cached under a key that omits tenant identity, a later request may reuse another tenant's data. The original query can be correct while cache identity is wrong.

    I resolve authenticated tenant membership first, use an appropriately scoped data key and reconsider freshness when permissions change. I keep secrets out of serialized cache arguments and tags.

    Follow-up questions

    • How do you test this with two sessions?
    • What happens after membership is revoked?
  5. 05A valid JWT says admin, but the user was demoted. Should the action accept it?

    It depends on the explicitly chosen authorization freshness policy. The signature proves the issuer signed the claim; it does not prove the role remains current.

    If demotion must take effect immediately, the action checks current permissions or a current policy/session version. A purely stateless unchanged token cannot communicate a later revocation by itself.

    Follow-up questions

    • How would short expiry change the risk window?
    • Does storing the token in an HttpOnly cookie fix stale roles?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

A verified token contains a tenant role that changed yesterday. Which claim is defensible?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.