logo

Database

Javascript Csrf Middleware Order Incorrect

Description

Detects when CSRF middleware is configured in the wrong order relative to other middleware in JavaScript web applications. This is a security risk because improper ordering can allow CSRF middleware to be bypassed, leaving the application vulnerable to Cross-Site Request Forgery attacks.

Weakness:

007 - Cross-site request forgery

Category: Access Subversion

Detection Strategy

    Review middleware configuration in application setup code (e.g., Express.js app configuration)

    Check if CSRF middleware is declared after body parsing or cookie parsing middleware

    Flag configurations where CSRF middleware is not the first middleware in the chain that processes request bodies

    Verify that CSRF middleware is initialized before any route handlers or application logic that needs CSRF protection

Vulnerable code example

const express = require('express');
const methodOverride = require('method-override');
const app = express();
const csrf = require('csurf');

// Vulnerable: methodOverride placed after CSRF protection allows bypass
app.use(csrf());  // CSRF protection is added first
app.use(methodOverride());  // Can bypass CSRF by overriding HTTP method...

✅ Secure code example

const express = require('express');
const methodOverride = require('method-override');
const csrf = require('csurf');
const app = express();

// Safe: methodOverride must be placed before CSRF protection
app.use(methodOverride());  // Method override middleware first
app.use(csrf());  // CSRF protection after method processing...