CSRF prevention

This commit is contained in:
Owen Schwartz 2024-12-25 22:04:20 -05:00
parent 03c1d7bb79
commit cccb46dc65
3 changed files with 43 additions and 8 deletions

View file

@ -0,0 +1,24 @@
import { NextFunction, Request, Response } from "express";
export function csrfProtectionMiddleware(
req: Request,
res: Response,
next: NextFunction
) {
const csrfToken = req.headers["x-csrf-token"];
// Skip CSRF check for GET requests as they should be idempotent
if (req.method === "GET") {
next();
return;
}
if (!csrfToken || csrfToken !== "x-csrf-protection") {
res.status(403).json({
error: "CSRF token missing or invalid"
});
return;
}
next();
}