Authentication vs Authorization: Fundamentals and Why Permissions Break
Authentication vs authorization, common permission pitfalls, the fail-closed principle, and the goals every permission system should meet.
Broken access control is the number one vulnerability in the OWASP Top 10 (2021, confirmed in the 2025 update, which also maps server-side request forgery into the category). Most permission bugs trace back to an architecture that makes checks easy to forget and hard to keep consistent. As a codebase grows, so does the number of places where a check can quietly go missing.
The default worth adopting from the first commit is a single permission-aware layer that every data access passes through, one that denies access whenever a check cannot complete. Getting there starts with a distinction that plenty of codebases blur.
Authentication vs Authorization#
These two concepts are often bundled under the single word “auth,” which leads to confusion. They are fundamentally different concerns.
Authentication answers: “Who are you?” It verifies identity: valid session tokens, JWTs, OAuth flows. The first answer is yes or no: either the request carries a valid session or it doesn’t. Sessions still differ in strength, such as whether the user passed MFA and how recently they signed in. NIST SP 800-63B groups authenticator strength into authentication assurance levels, each with its own reauthentication limit, and step-up authentication raises a session to a higher level when an action needs it. Authorization rules often read these properties, for example by requiring a fresh MFA prompt before someone changes billing details.
Authorization answers: “What can you do?” It evaluates permissions based on the user, the resource, and the action. It is contextual. A user might be allowed to edit their own documents but not someone else’s, even though they are fully authenticated.
The confusion between these two creates a common failure pattern: codebases that check whether a user is logged in but never check whether that user is allowed to perform a specific action.
The HTTP status codes reflect this distinction. A 401 Unauthorized response means the server doesn’t know who the user is (despite the confusing name, it means “unauthenticated”). A 403 Forbidden response means the server knows who the user is but they don’t have permission.
Tip
If your application returns 401 for permission failures or 403 for login issues, that’s a signal that authentication and authorization are being conflated in the codebase.
A 403 has one side effect: it confirms that the resource exists. For resources whose existence should stay hidden, such as a private project or another user’s document, answer with 404 both when the resource is missing and when the user may not see it. RFC 9110 allows this explicitly for an origin server that wants to hide a forbidden resource. Once the endpoint in Scenario 3 below gains a check, a 403 for existing IDs and a 404 for missing ones still lets an attacker walk sequential IDs and map which resources exist. Keep 403 for a user who can already see the resource but may not perform the action.
The Example Application#
Throughout this series, we’ll use a project and document management application as our running example. Here are the domain types:
interface User {
id: string;
email: string;
role: 'admin' | 'editor' | 'author' | 'viewer';
}
interface Project {
id: string;
name: string;
ownerId: string;
visibility: 'public' | 'private';
members: ProjectMember[];
}
interface ProjectMember {
userId: string;
role: 'editor' | 'author' | 'viewer';
}
interface Document {
id: string;
projectId: string;
title: string;
content: string;
authorId: string;
status: 'draft' | 'review' | 'published';
}
The intended permissions:
- Admin: Full access to everything
- Editor: Can edit and publish documents in projects they belong to
- Author: Can create and edit their own documents, submit for review
- Viewer: Can read published documents in projects they have access to
Simple enough in theory. In practice, this is where things break down.
Naive Permission Pitfalls#
Scattered Permission Checks#
The most common anti-pattern is permission logic duplicated across pages, server actions, and API routes, with each copy drifting slightly from the others.
Page component (app/projects/[id]/page.tsx):
// Permission check #1: in the page component
export default async function ProjectPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const session = await getSession();
const project = await db.project.findUnique({
where: { id },
include: { members: true },
});
if (!project) {
notFound(); // 404: no such project
}
if (project.visibility === 'private') {
if (!session) {
redirect('/login'); // 401 equivalent; also leaks existence
}
const isMember = project.members.some(
(m) => m.userId === session.userId
);
// Bug: this redirect tells a non-member that
// the private project exists
if (!isMember && session.user.role !== 'admin') {
redirect('/unauthorized');
}
}
return <ProjectView project={project} />;
}
The notFound() and redirect('/login') guards matter. Without them, a missing project makes project.visibility throw a TypeError, and a private page opened without a session fails the same way on session.userId. The visitor gets a 500. That still denies access, so it fails closed, but it sends the wrong signal: a missing project should be a 404. The login redirect is the usual page answer to a missing session, yet it leaks existence the same way the /unauthorized redirect does: an anonymous visitor sent to log in has learned that the private project exists. A route that must hide private projects answers 404 to anonymous visitors as well. The two snippets below skip these guards, which adds to their own bugs.
Server action (app/actions/documents.ts):
// Permission check #2: similar but subtly different
'use server';
export async function updateDocument(
documentId: string,
content: string
) {
const session = await getSession();
const document = await db.document.findUnique({
where: { id: documentId },
});
// Bug: forgot to check project membership!
// Only checks if user is the author
if (document.authorId !== session.userId) {
throw new Error('Unauthorized');
}
// Bug: editors should be able to edit too,
// but this check excludes them
await db.document.update({
where: { id: documentId },
data: { content },
});
}
API route (app/api/projects/[id]/documents/route.ts):
// Permission check #3: yet another variation
export async function GET(
req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const session = await getSession();
// Bug: checks admin OR member but doesn't check
// project visibility. Public project documents
// should be accessible to everyone.
if (session.user.role !== 'admin') {
const project = await db.project.findUnique({
where: { id },
});
const isMember = project.members.some(
(m) => m.userId === session.userId
);
if (!isMember) {
return new Response('Forbidden', { status: 403 });
}
}
const documents = await db.document.findMany({
where: { projectId: id },
});
// Bug: returns ALL documents including drafts to viewers
return Response.json(documents);
}
Three locations carry three slightly different permission implementations, and each one has its own bug. Changing a rule like “editors can now also publish” means finding and updating every location by hand. Nothing in the codebase answers “can user X do action Y on resource Z?” in one place.
Over-Permission: Returning Too Much Data#
Another common pitfall is returning more data than a user should see:
export async function GET(
req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const session = await getSession();
const documents = await db.document.findMany({
where: { projectId: id },
include: { author: true, reviews: true },
});
// A viewer sees draft documents they shouldn't know about
// An author sees other authors' review feedback
// meant for editors only
return Response.json(documents);
}
The query returns everything, with no filtering based on what the user’s role allows them to see. A viewer gets draft documents, and an author gets review comments intended for editors. The API “works,” but it leaks data.
Inconsistent Checks Across Layers#
The same “can edit document” permission, checked differently in three places:
// UI component: checks by role string
function EditButton({ user, document }: Props) {
const canEdit =
user.role === 'admin' ||
user.role === 'editor' ||
document.authorId === user.id;
// Missing: doesn't check project membership
if (!canEdit) return null;
return <button>Edit</button>;
}
// Server action: checks differently
async function editDocument(docId: string, content: string) {
const session = await getSession();
const doc = await getDocument(docId);
// Different logic: checks author but forgets editor role
if (
doc.authorId !== session.userId &&
session.user.role !== 'admin'
) {
throw new Error('Cannot edit');
}
// ...
}
// Middleware: checks yet another way
export async function middleware(req: NextRequest) {
const session = await verifySessionCookie(req);
if (!session) {
return NextResponse.redirect(new URL('/login', req.url));
}
// Only checks authentication, not authorization
return NextResponse.next();
}
The result: the Edit button shows for the right users, but clicking it may fail (or worse, succeed when it shouldn’t) because the server-side check uses different logic than the client-side check.
Next.js-Specific Pitfalls#
Layout-based authorization is a common mistake in Next.js applications:
// app/dashboard/layout.tsx
export default async function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
const session = await getSession();
if (!session) {
redirect('/login');
}
// Problem 1: Layouts don't re-render on client-side navigation.
// The session check runs once but not on subsequent route changes.
// Problem 2: Server Actions in nested routes bypass this check.
// A server action can be called from anywhere.
// Problem 3: API routes under /dashboard are not protected
// by this layout either.
return <>{children}</>;
}
Middleware-only authorization is another trap, and a well-documented one. CVE-2025-29927 (CVSS 9.1) showed that the x-middleware-subrequest header in Next.js could be exploited to bypass all middleware-based access control entirely. Any protection that lived only in middleware could be circumvented with a single HTTP header.
The fix shipped in Next.js 15.2.3 and 14.2.25, with backports in 13.5.9 and 12.3.5. The advisory states that deployments hosted on Vercel were protected automatically, so the upgrade mattered most for self-hosted applications. If upgrading is not possible, the advisory’s workaround is to stop external requests that carry the x-middleware-subrequest header before they reach the application. Next.js 16 deprecates the middleware file convention and renames it to proxy (proxy.ts, with an exported proxy function). The rename leaves the lesson intact: the Proxy docs still recommend verifying authentication and authorization inside each Server Function instead of relying on Proxy alone.
// middleware.ts: vulnerable pattern
export async function middleware(request: NextRequest) {
// Must verify the cookie's signature; a helper that
// only decodes it would accept a forged session
const session = await verifySessionCookie(request);
if (request.nextUrl.pathname.startsWith('/admin')) {
if (!session || session.role !== 'admin') {
return NextResponse.redirect(
new URL('/login', request.url)
);
}
}
return NextResponse.next();
}
// CVE-2025-29927: An attacker could add an
// x-middleware-subrequest header to skip ALL middleware.
// Authorization must happen at the data access layer.
This vulnerability demonstrates a fundamental principle: authorization must happen at the data access layer, not only at the middleware or routing level. Defense in depth (checks at multiple layers) is essential.
The “Fail Closed” Principle#
When a permission check encounters an error (a database timeout, an unexpected exception, a missing field), there are two possible defaults:
Fail open (dangerous): Grant access when the check fails.
async function checkPermission(
userId: string,
resourceId: string
): Promise<boolean> {
try {
const permission = await db.permission.findFirst({
where: { userId, resourceId },
});
return permission !== null;
} catch (error) {
console.error('Permission check failed:', error);
return true; // FAIL OPEN: grants access on error
}
}
Fail closed (secure): Deny access when the check fails.
async function checkPermission(
userId: string,
resourceId: string
): Promise<boolean> {
try {
const permission = await db.permission.findFirst({
where: { userId, resourceId },
});
return permission !== null;
} catch (error) {
console.error('Permission check failed:', error);
return false; // FAIL CLOSED: denies access on error
}
}
A subtler version of this trap is the isAdmin boolean default:
// DANGEROUS: defaults to true
let isAdmin = true;
try {
const user = await getUser(session.userId);
isAdmin = user.role === 'admin';
} catch (error) {
logger.error('Failed to fetch user role', error);
// isAdmin remains true, so any error grants admin access
}
// SECURE: defaults to false
let isAdmin = false;
try {
const user = await getUser(session.userId);
isAdmin = user.role === 'admin';
} catch (error) {
logger.error('Failed to fetch user role', error);
// isAdmin remains false, so an error means no admin access
}
A fail-open path does not need a catch block at all. In Prisma, a filter field set to undefined is dropped from the query, which then behaves as if no filter was passed for that column. When a request has no session, the userId below is undefined, and the query asks whether any permission row exists for the resource:
const session = await getSession(); // null for an anonymous request
const permission = await db.permission.findFirst({
where: { userId: session?.userId, resourceId },
});
// userId: undefined is dropped from the filter, so this
// matches ANY permission row for the resource
const allowed = permission !== null; // true
No exception is thrown, so the catch in the fail-closed version never runs. The fix is to treat missing input as a denial before the query. A required userId: string parameter makes the compiler reject session?.userId at most call sites, and a runtime guard covers values that arrive from a session, a JSON body or an any:
async function checkPermission(
userId: string,
resourceId: string
): Promise<boolean> {
// The types say string, but a value read from a session,
// a JSON body or an `any` can still be undefined at runtime
if (!userId || !resourceId) {
return false;
}
try {
const permission = await db.permission.findFirst({
where: { userId, resourceId },
});
return permission !== null;
} catch (error) {
console.error('Permission check failed:', error);
return false;
}
}
Prisma’s strictUndefinedChecks preview feature closes the same gap at the client level: an explicit undefined in a query becomes a runtime error, which the fail-closed catch then turns into a denial.
The rule is straightforward: security methods like isAuthorized(), isAuthenticated(), and validate() should return false on any exception and on any missing input. When in doubt, deny access.
Warning
This applies to allowlists vs blocklists too. An allowlist (“only these roles can access”) fails closed: a new role has no access by default. A blocklist (“block these roles”) fails open: a new role has access until someone remembers to add it to the block list.
Goals of a Good Permission System#
Before building a solution, it helps to define what a good permission system should achieve. These goals will guide the rest of this series:
1. Prevent Unauthorized Access#
Both horizontal escalation (user A accessing user B’s data) and vertical escalation (a viewer performing admin actions) must be prevented. Every endpoint and every data query needs an authorization check that considers the specific user, resource, and action.
In a B2B product, horizontal escalation also has a tenant dimension: a user in one organization reaching another organization’s data. The example application has no tenant boundary yet. Post 106 adds one as a global condition in the permission layer.
2. Be Consistent#
The same permission logic must apply everywhere. If an editor can edit documents in the UI, the same rule must apply in server actions, API routes, and database queries. One source of truth for permission rules eliminates drift between layers.
3. Auto-Enforce by Default#
Developers should not need to remember to add permission checks. The system architecture should make the checked path the default one. If accessing data requires going through a permission-aware service layer, skipping the check takes deliberate effort. A service layer alone does not make the compiler object, though, because any file can still import the database client. Two mechanisms close that gap. ESLint’s no-restricted-imports rule can flag every import of the database module outside the service layer, so CI fails on a direct query. PostgreSQL row-level security goes one step further and enforces the rule inside the database: once it is enabled on a table, rows are visible only when a policy allows them. Superusers, roles with the BYPASSRLS attribute and, by default, the table owner bypass those policies, so the application connects as a separate role, or the table is set to FORCE ROW LEVEL SECURITY. The BOLA post covers RLS in practice.
4. Be Easy to Update#
Changing a permission rule, like “editors can now also publish,” should require a single change in a single place. If updating a permission rule requires searching the entire codebase for scattered checks, mistakes are inevitable.
5. Be Auditable#
Know who accessed what and when. Compliance requirements in fintech, healthcare, and other regulated industries demand access audit trails. Even outside regulated industries, audit logs are invaluable for debugging permission issues.
6. Be Performant#
Permission checks happen on every request, often multiple times per request. They cannot add significant latency. Caching strategies, efficient data structures, and minimal database queries are all considerations.
7. Be Type-Safe#
In TypeScript, the type system should catch permission errors at compile time. If a role is renamed, the compiler should flag every reference. If a permission check requires a resource object but receives undefined, the compiler should reject it before that code ever runs.
Real-World Scenarios: Permission Bugs in Practice#
Let’s walk through specific failure scenarios in the example application to see how these anti-patterns manifest.
Scenario 1: Horizontal Privilege Escalation#
User A is an author in Project X. They change the document ID in the URL from /projects/x/documents/123 to /projects/y/documents/456. The page component checks “is the user authenticated?” but never checks “does this user have access to Project Y?”
User A now reads documents from a project they have no relationship to.
Scenario 2: Vertical Privilege Escalation#
A viewer discovers that the “publish document” server action exists at a predictable endpoint. The UI hides the “Publish” button for viewers, but the server action only checks whether the user is authenticated, without ever checking their role.
The viewer publishes documents by calling the server action directly.
Scenario 3: IDOR (Insecure Direct Object Reference)#
The API endpoint /api/documents/123 returns the document if it exists in the database. No check for whether the requesting user has any relationship to the document or its project. Sequential IDs make enumeration trivial: an attacker iterates through IDs and downloads every document in the system.
Scenario 4: Inconsistent Role Enforcement#
The admin panel is accessible via the UI only to admins (a client-side check hides the navigation link). But the admin API routes (/api/admin/users, /api/admin/settings) lack role verification. Any authenticated user who knows the URL can call admin APIs directly.
Every one of these scenarios shares a root cause: authorization logic that is scattered, duplicated, or missing entirely.
Common Pitfalls Summary#
| Approach | Advantage | Problem |
|---|---|---|
| Ad-hoc scattered checks | Quick to implement initially | Inconsistent, unmaintainable, creates security gaps |
| Middleware-only checks | Runs on every request | Bypassable (CVE-2025-29927), no resource-level context |
| Layout-based checks | Feels centralized | Does not re-render on navigation, does not protect server actions |
| Client-side-only checks | Good UX (hides inaccessible UI) | Zero security value; the server must always verify |
What’s Next#
Centralization is the way out of the scattered checks above. In the next post, we’ll introduce the service layer pattern: a single layer that all data access passes through, where authorization is checked once and checked correctly.
// Preview: full implementation in Post 102
// Instead of scattered checks everywhere,
// all access goes through a permission-aware service:
const document = await documentService.getById(
session.userId,
documentId
);
// The service handles: authentication, authorization,
// and data filtering.
// If the user can't access this document, the service
// throws before the page renders.
A service layer holds as the default whenever application code and the database are separated by a real boundary, because a page, a server action, and an API route then share one rule instead of three copies of it. That guarantee disappears the moment someone queries the database directly, so the boundary has to be enforced in code; documenting it is not enough.
References#
- OWASP Top 10:2025 - A01 Broken Access Control (opens in new tab) - Broken access control is the number one web application security risk, confirmed in both the 2021 and 2025 editions; the 2025 edition also maps SSRF (CWE-918) into it
- OWASP Authorization Cheat Sheet (opens in new tab) - Comprehensive best practices for authorization including deny by default and server-side enforcement
- OWASP Fail Securely (opens in new tab) - Why security methods should return false on exception, with the isAdmin default trap example
- CVE-2025-29927: Next.js Middleware Authorization Bypass (ProjectDiscovery) (opens in new tab) - Technical analysis of the CVSS 9.1 vulnerability allowing middleware bypass via the x-middleware-subrequest header
- CVE-2025-29927: Next.js Authorization Bypass (JFrog) (opens in new tab) - Detailed breakdown of affected versions, exploit mechanism, and mitigation strategies
- Next.js Authentication Guide (Official) (opens in new tab) - Official documentation covering the Data Access Layer pattern, middleware limitations, and server action security
- Authorization Bugs Are Having Their SQL Injection Moment (ZeroPath) (opens in new tab) - Analysis showing 53% of critical vulnerabilities are access control flaws with near-zero SAST detection rates
- How to Avoid Common Authorization Errors (Cerbos) (opens in new tab) - Catalog of authorization anti-patterns including over-permissions and inconsistent logic
- Understanding Fail Open and Fail Closed (AuthZed) (opens in new tab) - Detailed explanation of fail-open vs fail-closed patterns with code examples
- Authentication vs. Authorization (Microsoft Identity Platform) (opens in new tab) - Authoritative documentation on the authentication and authorization distinction
- Next.js Middleware Authorization Bypass Advisory (GHSA-f82v-jwr5-mffw) (opens in new tab) - The official advisory for CVE-2025-29927, with patched versions per release line, the header-stripping workaround and the note on Vercel-hosted deployments
- proxy.js File Convention (Next.js) (opens in new tab) - Documents the Next.js 16 rename of
middlewaretoproxyand the advice to verify authorization inside each Server Function - Null and undefined (Prisma) (opens in new tab) - How Prisma drops
undefinedfilter fields from a query, and thestrictUndefinedCheckspreview feature that turns them into errors - RFC 9110: HTTP Semantics, 403 Forbidden (opens in new tab) - The HTTP specification, which allows a server to answer with 404 to hide that a forbidden resource exists
- NIST SP 800-63B: Authentication and Authenticator Management (opens in new tab) - Defines authentication assurance levels, reauthentication timeouts and step-up authentication
- no-restricted-imports (ESLint) (opens in new tab) - The lint rule that disallows chosen modules, with a custom message per restricted path
- Row Security Policies (PostgreSQL) (opens in new tab) - How row-level security applies default-deny policies, and which roles bypass them
Permission Systems that Scale
Part 1 of 6A comprehensive guide to building scalable permission systems in TypeScript and Next.js, progressing from naive checks through RBAC and ABAC to production-grade multi-tenant authorization.
All posts in this series
Related posts
Refactor scattered permission checks into a centralized service layer, add Next.js middleware guards, and build a defense-in-depth authorization architecture.
typescript · nextjs · authorization +2
Build a type-safe RBAC system in TypeScript, create a unified can() function, sync permissions across UI and backend, and learn when RBAC reaches its limits.
typescript · nextjs · authorization +2
Build an ABAC policy engine in TypeScript with the builder pattern, conditional permissions, and type-safe policy evaluation that replaces RBAC's limitations.
typescript · nextjs · authorization +2
Extend ABAC with environment-based rules, field-level read and write permissions, and automatic database query filtering that eliminates duplicate permission logic.
typescript · nextjs · authorization +2
Add multi-tenant isolation to your permission system, evaluate CASL as a library alternative, and use decision frameworks to choose the right authorization architecture.
typescript · nextjs · authorization +3