Mastering CSRF Protection in Laravel: Tokens, Whitelists, and JavaScript Integration
This guide explains how Laravel automatically generates CSRF tokens, how to embed them in Blade forms, configure the VerifyCsrfToken middleware, whitelist routes, and integrate token handling with JavaScript libraries such as Axios and jQuery for robust request protection.
CSRF Protection Overview
Cross‑Site Request Forgery (CSRF) is an attack that forces an authenticated user’s browser to perform unwanted actions on a web application. Laravel mitigates this by generating a unique CSRF token for each active session and storing it server‑side.
Adding CSRF Token to Forms
Every HTML form that submits data via POST, PUT, PATCH or DELETE must include a hidden input containing the token. In Blade templates the @csrf directive injects the appropriate input element.
<form method="POST" action="/profile">
@csrf
<!-- other fields -->
</form>CSRF Middleware Verification
The VerifyCsrfToken middleware, part of the web middleware group, automatically compares the token submitted with the request to the token stored in the session. If they differ, the request is rejected with a 419 status.
Token Access from JavaScript
Laravel places the current token in an encrypted XSRF‑TOKEN cookie. The default Axios instance defined in resources/js/bootstrap.js reads this cookie and adds an X‑XSRF‑TOKEN header to every outgoing request. When using a different HTTP client (e.g., fetch, jQuery), you must manually read the token and set the header.
<meta name="csrf-token" content="{{ csrf_token() }}"> // Example with jQuery
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});Excluding Routes from CSRF Verification (Whitelist)
Some endpoints, such as external webhooks, cannot provide a CSRF token. Those routes can be excluded by adding their URIs to the $except property of the VerifyCsrfToken middleware.
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'stripe/*',
'webhook/third‑party/*',
];
}During automated tests Laravel automatically disables the CSRF middleware, so tokens are not required.
Header‑Based Token Submission
In addition to the hidden form field, Laravel also accepts the token via the X‑CSRF‑TOKEN request header. Placing the token in a meta tag (as shown above) and configuring the client to read it ensures that AJAX requests are protected without modifying each request manually.
Cookie‑Based Token Submission
The XSRF‑TOKEN cookie is sent with every response. Front‑end frameworks such as Angular, Axios, or the default Laravel Axios instance automatically read this cookie and include its value in the X‑XSRF‑TOKEN header. If you disable the default Axios configuration, replicate the same behavior in your client.
Default Laravel installation: resources/js/bootstrap.js registers an Axios interceptor that adds the X‑XSRF‑TOKEN header.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
