Implementing Authorization Middleware
1. Creating Authentication Middleware
Example: Express
async function authenticate(req, res, next) {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) return res.status(401).end();
try { req.user = await verifyJwt(token); next(); }
catch { res.status(401).end(); }
}
2. Building Authorization Middleware
Example: Permission guard
const require = (perm) => (req, res, next) =>
req.user?.permissions.includes(perm) ? next() : res.status(403).end();
router.delete("/orders/:id", authenticate, require("orders:delete"), handler);
3. Implementing Middleware Chains
| Order | Reason |
|---|---|
| CORS | First (allow preflight) |
| Logging | Capture all requests |
| Rate limit | Before auth (protect login) |
| Authenticate | Establish identity |
| Authorize | Check permission |
| Handler | Business logic |
4. Using Role-Based Middleware
Example
const requireRole = (...roles) => (req, res, next) =>
roles.some(r => req.user?.roles.includes(r)) ? next() : res.status(403).end();
5. Implementing Permission-Based Middleware
Example: Resource-aware
const can = (action, loader) => async (req, res, next) => {
const resource = await loader(req);
if (!await pdp.check(req.user, action, resource)) return res.status(403).end();
req.resource = resource; next();
};
6. Creating Conditional Middleware
Example: Skip auth for public routes
const optionalAuth = async (req, res, next) => {
const t = req.headers.authorization?.replace("Bearer ", "");
if (t) { try { req.user = await verify(t); } catch {} }
next();
};
7. Handling Middleware Errors
| Approach | Detail |
|---|---|
| Express | Pass next(err); error handler returns standard shape |
| RFC 7807 | application/problem+json |
| Don't leak | Generic message; details to logs |
8. Implementing Reusable Guards
| Framework | Pattern |
|---|---|
| NestJS | @UseGuards(JwtAuthGuard, RolesGuard) |
| Spring | @PreAuthorize on methods |
| Next.js | middleware.ts at route segment |
9. Using Middleware for Route Protection
| Grouping | Detail |
|---|---|
| Router-level | app.use("/admin", requireRole("admin")) |
| Route-level | Per-route middleware list |
| Annotation | Decorators in Nest/Spring |
10. Implementing Middleware in Express/Nest
Example: NestJS guard
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(ctx: ExecutionContext) {
const required = this.reflector.get<string[]>("roles", ctx.getHandler());
if (!required) return true;
const { user } = ctx.switchToHttp().getRequest();
return required.some(r => user?.roles?.includes(r));
}
}