Next.js Middleware Authorization Bypass
Description
Next.js versions 11.1.4 through 13.5.6, 14.x before 14.2.25, and 15.x before 15.2.3 contain an authorization bypass vulnerability that allows attackers to circumvent middleware-based security controls by injecting a specially crafted x-middleware-subrequest header into HTTP requests. This vulnerability affects all middleware functionality including authentication checks, authorization logic, path rewrites, server-side redirects, and security header injection (such as Content Security Policy). Attackers can exploit this flaw to access protected routes and resources as if middleware security controls were not present.
Remediation
Take the following steps to remediate this vulnerability:
1. Immediate Action - Update Next.js:
Upgrade to a patched version immediately:
• Version 13.5.7 or later (for 13.x users)
• Version 14.2.25 or later (for 14.x users)
• Version 15.2.3 or later (for 15.x users)
2. Implement Defense-in-Depth:
Do not rely solely on middleware for security controls. Add additional authorization checks in your API routes and server components:
// Example: Add authorization checks in API routes
export async function GET(request) {
// Verify authentication at the handler level
const session = await getServerSession();
if (!session || !session.user) {
return new Response('Unauthorized', { status: 401 });
}
// Verify authorization for specific resources
if (!hasPermission(session.user, 'resource:read')) {
return new Response('Forbidden', { status: 403 });
}
// Process authorized request
return Response.json({ data: sensitiveData });
}3. Validate Authentication Tokens:
Implement server-side validation of authentication tokens in your API handlers and server components, independent of middleware checks.
4. Apply Database-Level Access Controls:
Ensure your database queries include user context and permission checks to prevent unauthorized data access even if application-level controls are bypassed.
5. Verification:
After updating, test that middleware continues to function correctly and verify that protected routes cannot be accessed by adding the
x-middleware-subrequest header to requests.