CSRF Protection
- Introduction
- Complete Example: Blade Form and Rejection Test
- Preventing CSRF Requests
- JavaScript Requests
- How It Works
Introduction
Cross-site request forgery (CSRF) is an attack where another site makes a logged-in user's browser submit a request to your application. DotBlaze protects every state-changing request with ASP.NET Core antiforgery tokens, the same idea as Laravel's @csrf token.
Preventing CSRF Requests
The csrf middleware, part of the web middleware group that every route gets by default, validates a CSRF token on every POST, PUT, PATCH, and DELETE request. GET, HEAD, OPTIONS, and TRACE requests are not checked. A request without a valid token is rejected with the 419 | Page Expired error page, which you can replace with a resources/views/errors/419 view (see Error Handling) (for JSON requests: { "message": "CSRF token mismatch." }) before your action runs, like in Laravel.
Forms With an action Attribute
WARNING
Every form that posts and has an explicit action attribute must contain @Csrf(). Without it the form gets a 419 | Page Expired on submit.
@Csrf() renders a hidden __RequestVerificationToken input, like Blade's @csrf:
<form method="post" action="@Route("login")">
@Csrf()
<input type="email" name="Email" />
<input type="password" name="Password" />
<button type="submit">Log in</button>
</form>This also applies to forms that use method spoofing:
<form method="post" action="@Route("posts.destroy", new { post = Model.Id })">
@Csrf()
@Method("DELETE")
<button type="submit">Delete</button>
</form>Forms Without an action Attribute
The ASP.NET Core form tag helper adds the token automatically, but only when the <form> has no action attribute (it posts to the current URL) or uses asp-* attributes such as asp-action. DotBlaze's views use named routes and explicit action attributes, so in practice you should add @Csrf() to every form. Adding it to a form that also gets the tag helper token is harmless.
Excluding Actions From CSRF Protection
Laravel excludes URIs in its middleware configuration. In DotBlaze, leave the middleware out of the route, for example for a webhook that a third-party service posts to:
Route.Post<WebhookController>("/webhooks/stripe", c => c.Stripe).WithoutMiddleware("csrf");ASP.NET Core's [IgnoreAntiforgeryToken] attribute on the action or controller works too:
using Microsoft.AspNetCore.Mvc;
public class WebhookController : BaseController
{
[IgnoreAntiforgeryToken]
public IActionResult Stripe() => Ok();
}Routes in the api group (routes/api.cs) require CSRF tokens for cookie-authenticated writes. Bearer-only and anonymous requests do not require a CSRF token. A login cookie takes precedence over a bearer header, so adding that header does not bypass the cookie check.
JavaScript Requests
JavaScript requests may send the token in the RequestVerificationToken header instead of a form field. Render @Csrf() somewhere on the page and read its value:
@Csrf()
<script>
const token = document.querySelector('input[name="__RequestVerificationToken"]').value;
fetch('/posts', {
method: 'POST',
headers: { 'RequestVerificationToken': token, 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ Title: 'Hello', Body: 'From fetch' }),
});
</script>The browser must also send the antiforgery cookie, which it does automatically for same-origin fetch calls.
How It Works
- The check is the
csrfroute middleware (ValidateCsrfToken) in thewebgroup, so it applies to every route registered withRoute.*that is not in theapigroup. - It runs before the route's own middleware: a guest posting without a token to an
authroute gets419, not a redirect to the login page. - The
_methodoverride is applied before the check, so a spoofedDELETEis validated like any other unsafe request. - Tokens are protected with ASP.NET Core Data Protection, the same key ring used by encryption. The keys are persisted to
storage/framework/keysby default. If your application runs on several servers, they must share that folder (or another key store) or tokens issued by one server are rejected by another.
Complete Example: Blade Form and Rejection Test
The earlier @Csrf() examples are Razor syntax. For the generated Blade views, use @csrf (or {{ Csrf() }}). The walkthrough's form includes it in every POST, PUT, and DELETE form.
For example, inside its Show.blade.html:
@can('delete', Model)
<form method="post" action="{{ Route('posts.destroy', new { post = Model.Id }) }}">
@csrf
@method('DELETE')
<button type="submit">Delete this post</button>
</form>
@endcanThe complete HTTP test includes a request with WithoutCsrfToken() and expects 419, followed by a successful authenticated update using the normal test client. Keeping an auth cookie alone is not sufficient for web writes; the request also needs the token bound to that browser session.
For multi-server applications, use the same APP_KEY and app.name, or share the generated Data Protection keys when no APP_KEY is configured. Excluding a webhook from CSRF only removes this browser-origin protection; authenticate the webhook using its provider's signature.