Express authorization middleware: Check the user and resource together
Authorization middleware decides on the server whether an already identified user may perform a particular action, and passes only permitted requests to the next handler. Using a document-editing API in Express 5, this article explains object-level permissions that role checks can miss, deny-by-default behavior, 401 and 403 responses, and middleware placement. Policy rules are injected by the service; the sample code has not been compiled or run.
Authorization middleware decides on the server whether an already identified user may perform a particular action, and passes only permitted requests to the next handler. Using a document-editing API in Express 5, this article explains object-level permissions that role checks can miss, deny-by-default behavior, 401 and 403 responses, and middleware placement. Policy rules are injected by the service; the sample code has not been compiled or run.
How is authorization different from authentication?
Authentication establishes who a request represents. Authorization decides whether that subject may perform a specific action on a specific resource. A successful login or valid token does not grant access to every account, document, or administrative operation. Public routes may allow unauthenticated access, but each non-public API endpoint needs an access-control decision. (OWASP: Authorization Cheat Sheet, OWASP: REST Security Cheat Sheet)
Express middleware can access the request, response, and next step. If authorization succeeds, it calls next(); if access is denied, it ends the response without running the protected operation. Unexpected failures in a policy service or data store should go to error handling rather than being disguised as an ordinary denial. (Express: Writing middleware)
Why are role checks alone insufficient?
Role-based access control (RBAC) is useful for permissions attached to roles, but users with the same role do not necessarily have access to one another’s documents. A decision may need to consider the subject, resource, relationship, tenant, resource state, and requested action. OWASP recommends checking permissions for every request and object, with access denied by default. (OWASP: Authorization Cheat Sheet)
For example, user A may read their own document, but a request that changes the URL to user B’s document ID must be checked separately and denied. An unguessable UUID does not replace authorization. Apply the same scope to list, search, and export operations. (OWASP: IDOR Prevention Cheat Sheet)
How can Express 5 check permission for a document?
The TypeScript example below assumes an earlier authentication step has put a verified user ID in req.principal. It loads the document and passes the user, action, and resource to a policy function. Implement the actual ownership, tenant, and data-access rules for your application.
import type { RequestHandler } from 'express';
type Principal = { subject: string };
type Document = { id: string; ownerId: string; tenantId: string };
type Action = 'read' | 'edit';
declare global {
namespace Express {
interface Request {
principal?: Principal;
document?: Document;
}
}
}
interface DocumentStore {
findById(id: string): Promise<Document | null>;
}
interface DocumentPolicy {
allows(input: {
subject: Principal;
action: Action;
resource: Document;
}): Promise<boolean>;
}
export function requireDocumentPermission(
action: Action,
store: DocumentStore,
policy: DocumentPolicy,
): RequestHandler {
return async (req, res, next) => {
if (!req.principal) {
res.sendStatus(401);
return;
}
try {
const document = await store.findById(req.params.documentId);
if (!document) {
res.sendStatus(404);
return;
}
const allowed = await policy.allows({
subject: req.principal,
action,
resource: document,
});
if (!allowed) {
res.sendStatus(403);
return;
}
req.document = document;
next();
} catch (error) {
next(error);
}
};
}The policy must explicitly allow access; a missing rule, policy error, or incomplete input must not become an allow decision. Returning 404 for a missing document is one API choice. A service that must conceal whether a resource exists may use the same response for unauthorized access, provided its policy and response contract are consistent. Store or policy-service outages are passed into server error handling, not reported as 403; keep internal details out of client responses. (OWASP: Authorization Cheat Sheet)
How should the route be ordered?
Run authentication first, then document authorization, then the protected handler. This example assumes the authentication middleware, policy, and store are configured elsewhere.
router.patch(
'/documents/:documentId',
requireAuthentication(tokenVerifier),
requireDocumentPermission('edit', documentStore, documentPolicy),
async (req, res) => {
const updated = await documentService.update(req.document!, req.body);
res.json(updated);
},
);Express runs middleware in registration order. If the protected handler is registered first, or a URL or HTTP-method path omits the check, a bypass can remain. Check alternate access paths such as downloads, attachments, and administrative operations too. (Express: Using middleware, OWASP: Authorization Cheat Sheet)
Should list and search APIs use the same middleware?
Per-document middleware fits an operation that names one object. For lists and searches, constrain the data-store query to the tenants, projects, and documents the current user can access instead of fetching everything and hiding some results afterward. Include counts, aggregates, exports, and static-file responses in the same access scope. (OWASP: Authorization Cheat Sheet)
A role check may provide a coarse boundary for administrative operations, but it does not decide object ownership or relationships. Hiding a button in a browser improves the interface; it is not a server-side authorization check. Make the decision on the trusted server or API layer for every request. (OWASP: Authorization Cheat Sheet)
How should denials and checks be handled?
Missing or invalid authentication usually maps to `401`; an authenticated subject without permission usually maps to `403`. A consistent `404` policy may conceal resource existence. Follow the API’s response contract. ([OWASP: REST Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html))
Deny by default and check every request, action, and object.
Do not trust `ownerId`, `tenantId`, or `role` from an unverified request body or header. Use the authenticated subject and resource attributes obtained by the server.
Do not expose internal policy details, database structure, or stack traces in denial responses. Log only the information needed to investigate who was denied for which action and resource; exclude secrets.
Use separate users A and B to check read, update, delete, list, search, export, and alternate paths. This article’s code is illustrative; these checks were not run against an application. ([OWASP: IDOR Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html), [OWASP: Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html))