Back to all terms
Authentication
Authbasic

Auth Middleware / Guards

Reusable middleware or guard components that intercept requests to enforce authentication and authorization policies before they reach route handlers.

Also known as: Authentication Middleware, Authorization Guards, Route Guards, Auth Interceptors, Policy Middleware

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

middlewareguardsinterceptorspipelineenforcementroute-protection