Framework Defaults
Most web frameworks ship a CSRF middleware that does the right thing by default. Trust the framework defaults and turn them on for every state-changing route — rolling your own goes wrong more often than not.
The defaults for every major framework
EXAMPLE
// Laravel — middleware is global, applies to all web routes
// app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\VerifyCsrfToken::class,
// …
],
];
// In Blade
<form method="POST" action="/transfer">
@csrf
…
</form>
// Express + csurf (or @fastify/csrf-protection on Fastify)
import csrf from 'csurf';
const csrfProtection = csrf({ cookie: { sameSite: 'lax', secure: true } });
app.use(csrfProtection);
app.get('/form', (req, res) => res.render('form', { csrfToken: req.csrfToken() }));
// Django — built-in middleware on by default
# settings.py — MIDDLEWARE already includes 'django.middleware.csrf.CsrfViewMiddleware'
# template tag
{% csrf_token %}
# class-based views: the decorator is applied automatically
// Rails — Action Controller has protect_from_forgery by default since 5.2
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
// ASP.NET Core MVC
services.AddAntiforgery(o => o.HeaderName = "X-CSRF-TOKEN");
// In Razor
<form asp-controller="Account" asp-action="Logout" method="post">
@Html.AntiForgeryToken()
<button>Sign out</button>
</form>
// SPA + cookie auth — same protection still applies. Read the cookie, send it
// back as a header your origin-locked API verifies.
Why it matters
When a framework ships a CSRF middleware by default, every “disable it for /api” PR should require justification. Most APIs ARE state-changing endpoints — they need the protection.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// Laravel: VerifyCsrfToken middleware enabled by default.
// Django: django.middleware.csrf.CsrfViewMiddleware + {% csrf_token %}
// Rails: protect_from_forgery with: :exception
// Express: csurf or @fastify/csrf-protection
Try it Yourself »
Exercise
Laravel middleware that enforces a CSRF token.
App\Http\Middleware\
PascalCase.
Discussion
Loading…