csrfProtection.ts 548 B

123456789101112131415161718192021222324
  1. import { NextFunction, Request, Response } from "express";
  2. export function csrfProtectionMiddleware(
  3. req: Request,
  4. res: Response,
  5. next: NextFunction
  6. ) {
  7. const csrfToken = req.headers["x-csrf-token"];
  8. // Skip CSRF check for GET requests as they should be idempotent
  9. if (req.method === "GET") {
  10. next();
  11. return;
  12. }
  13. if (!csrfToken || csrfToken !== "x-csrf-protection") {
  14. res.status(403).json({
  15. error: "CSRF token missing or invalid"
  16. });
  17. return;
  18. }
  19. next();
  20. }