Auth Middleware / Guards
Reusable middleware or guard components that intercept requests to enforce authentication and authorization policies before they reach route handlers.
Description
Auth middleware and guards are reusable components in the request processing pipeline that enforce authentication (verifying identity) and authorization (checking permissions) before a request reaches the business logic handler. They intercept incoming requests, validate credentials (session cookies, JWTs, API keys), resolve the caller's identity and permissions, and either allow the request to proceed or reject it with an appropriate error response (401 Unauthorized for authentication failures, 403 Forbidden for authorization failures).
Middleware and guards operate at different levels of granularity. Global middleware can enforce authentication across all routes. Route-level middleware or decorators can apply specific authorization requirements per endpoint. Guard patterns (common in NestJS, Angular, and Spring Security) use a canActivate interface that returns a boolean or throws an exception. The chain-of-responsibility pattern allows composing multiple guards: first verify authentication, then check roles, then validate resource ownership.
Best practices include separating authentication middleware (who are you?) from authorization middleware (what can you do?), implementing a consistent error response format across all guards, using dependency injection for testability, caching authorization decisions for repeated checks within a single request, and providing bypass mechanisms for health checks and public endpoints. The middleware should populate a request context (req.user, req.permissions) that downstream handlers can use without re-performing authentication. For microservices, consider a centralized API gateway that handles authentication and passes verified identity headers (X-User-ID, X-User-Roles) to backend services, with backend services validating that requests originate from the trusted gateway.
Prompt Snippet
Implement a layered auth middleware stack: (1) AuthenticationMiddleware that extracts the JWT from the Authorization: Bearer header, validates it (signature, exp, iss, aud), and populates req.user with decoded claims; (2) RequiresAuth decorator/guard that rejects unauthenticated requests with 401; (3) RequiresRole('admin') guard that checks req.user.roles and returns 403 if insufficient; (4) RequiresPermission('orders:write') guard that checks granular permissions. Use NestJS guards with canActivate or Express middleware with next(). Apply guards via decorators at the controller/route level. Skip auth for health-check and public routes using a @Public() decorator that sets metadata checked by the global guard.Tags
Related Terms
RBAC (Role-Based Access Control)
An access control model where permissions are assigned to roles, and users are granted roles, simplifying permission management at scale.
ABAC (Attribute-Based Access Control)
An access control model that evaluates policies against attributes of the user, resource, action, and environment to make authorization decisions.
JWT (JSON Web Tokens)
A compact, URL-safe token format that encodes claims as a JSON object, digitally signed for integrity verification and optionally encrypted for confidentiality.
Session Management
The practice of securely creating, maintaining, and destroying user sessions to track authenticated state across stateless HTTP requests.
Scope-Based Permissions
A permission model where access tokens carry scope strings that define the specific actions and resources the token is authorized to access.
Privilege Escalation Prevention
Security measures that prevent users from gaining unauthorized access to resources or functions beyond their assigned permissions, whether by elevating their own role or accessing other users' data.