CSRF middleware ordering

CSRF middleware ordering

Description

When an Express app allows HTTP method overrides, run CSRF validation against the final method. Otherwise the validator and the route may treat the same request differently.

Potential impact

A state change may run with the signed-in user’s permissions even though it never received the intended token check. The session secret itself need not be exposed.

Remediation

Apply method override before CSRF validation. Limit which original methods can be overridden, and check tokens on state-changing requests. The current method-override middleware accepts original POST requests by default. Review that restriction before broadening it.

Examples

These historical Express 3 excerpts omit body parsing, cookies, sessions and token issuance. For new code, use supported Express and CSRF implementations.

Before

javascript
const express = require('express');
const app = express();

app.use(express.csrf()); // CSRF middleware runs first
app.use(express.methodOverride());

app.post('/update', function(req, res) {
  // Application data-handling logic
  res.send('done');
});

After

javascript
const express = require('express');
const app = express();

app.use(express.methodOverride()); // Run methodOverride first
app.use(express.csrf()); // Then apply CSRF middleware

app.post('/update', function(req, res) {
  // Application data-handling logic
  res.send('done');
});

Explanation:

  • Before: CSRF validation runs before the method is finalized. Whether this leaves a state change unchecked depends on the permitted overrides.
  • After: The CSRF middleware sees the final method. It still needs a correctly configured session and valid token checks.

References