Missing CSRF protection middleware

Cross-site request forgery (CSRF)

Description

Browsers can send a signed-in user’s session cookie with a request the user did not intend. Express routes that change state need a way to verify the request before acting.

Potential impact

An unintended request can change an email address or permissions, place an order or initiate a payment using the user’s session.

Remediation

Use maintained CSRF protection globally or on every state-changing POST, PUT, PATCH and DELETE route. Issue a token, accept it from a hidden form field or X-CSRF-Token header and validate it on the server. Keep GET free of state changes. Use SameSite=Lax or SameSite=Strict as appropriate, and check the Origin or Referer on sensitive routes. For sensitive actions, consider reauthentication or CAPTCHA.

Examples

Before

javascript
const express = require("express");
const session = require("express-session");

const app = express();
// Run only behind one trusted TLS proxy; do not expose the application directly.
app.set("trust proxy", 1);
app.use(express.urlencoded({ extended: false }));
const sessionSecret = process.env.SESSION_SECRET;
if (!sessionSecret || sessionSecret.length < 32) {
  throw new Error("SESSION_SECRET must contain at least 32 characters");
}
app.use(
  session({
    secret: sessionSecret,
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true, secure: true, sameSite: "lax" },
  })
);

// Before: session authentication without CSRF protection middleware.
app.post("/account/email", (req, res) => {
  const userId = req.session.userId;
  const newEmail = req.body.email;
  // ... Update the email address in the database.
  res.send("updated");
});

app.listen(3000);

After

javascript
const express = require("express");
const session = require("express-session");
const { csrfSync } = require("csrf-sync");

const { csrfSynchronisedProtection, generateToken } = csrfSync({
  getTokenFromRequest(req) {
    if (req.is("application/x-www-form-urlencoded")) {
      return req.body.csrfToken;
    }
    return req.headers["x-csrf-token"];
  },
});

const app = express();
// Run only behind one trusted TLS proxy; do not expose the application directly.
app.set("trust proxy", 1);
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
const sessionSecret = process.env.SESSION_SECRET;
if (!sessionSecret || sessionSecret.length < 32) {
  throw new Error("SESSION_SECRET must contain at least 32 characters");
}
app.use(
  session({
    secret: sessionSecret,
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true, secure: true, sameSite: "lax" },
  })
);

// Apply CSRF token validation to all state-changing routes.
app.use(csrfSynchronisedProtection);

// Use the hidden `csrfToken` form field or the `x-csrf-token` header for JSON requests.
app.get("/account/email", (req, res) => {
  res.json({ csrfToken: generateToken(req) });
});

// After: reject requests without a token.
app.post("/account/email", (req, res) => {
  const userId = req.session.userId;
  const newEmail = req.body.email;
  // ... Update the database.
  res.send("updated");
});

app.listen(3000);

Explanation:

  • Before: The route has no token check. Its secure cookie settings and session secret do not establish the user’s intent. Both excerpts assume one trusted TLS proxy and no direct access to the app.
  • After: Get the token from GET /account/email. Send it in the csrfToken field for URL-encoded forms or the X-CSRF-Token header for JSON. After body parsing and session setup, csrfSynchronisedProtection validates the token.

References