Laravel - CSRF Protection

Laravel - CSRF Protection

CSRF Protection in Laravel

Certainly! CSRF (Cross-Site Request Forgery) protection is an important security measure in Laravel to prevent unauthorized commands from being executed on behalf of an authenticated user. Below is a detailed step-by-step guide to implementing and managing CSRF protection for POST requests in Laravel.

Step 1: CSRF Protection in Laravel

Laravel automatically generates and verifies CSRF tokens to protect against CSRF attacks. Any form that performs a POST, PUT, PATCH, or the DELETE request must include a CSRF token.

Step 2: Enabling CSRF Protection

By default, Laravel includes CSRF protection through middleware. You can find it in:

app/Http/Kernel.php

Look for the VerifyCsrfToken middleware in the $middlewareGroups array:

protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, // CSRF Protection Middleware ], ];

This ensures that all routes in the web middleware groups are protected.

Step 3: Adding CSRF Token to Forms

Whenever you create a form in Laravel that submits a POST, PUT, PATCH, or DELETE request, you must include a CSRF token.

Using Blade Syntax

Add the @csrf directive inside your form:

<form action="{{ route('post.submit') }}" method="POST"> @csrf <input type="text" name="name" placeholder="Enter Name"> <button type="submit">Submit</button> </form>

The @csrf directive generates a hidden input field like this:

<input type="hidden" name="_token" value="generated_csrf_token">

Step 4: Manually Retrieving CSRF Token

If you're making an AJAX request or using JavaScript frameworks like Vue.js or React, you must manually pass the CSRF token.

1. Adding CSRF Token to AJAX Requests (jQuery)

If you are using jQuery for an AJAX POST request, include the token in the headers:

$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.post("/submit", { name: "John Doe" }, function(data) { console.log(data); });

You can set the token in your Blade template:

<meta name="csrf-token" content="{{ csrf_token() }}">

2. Adding CSRF Token in JavaScript Fetch API

If you're using fetch(), include the CSRF token in the headers:

fetch('/submit', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }, body: JSON.stringify({ name: "John Doe" }) }).then(response => response.json()) .then(data => console.log(data));

Step 5: Handling CSRF Token Verification Errors

If a request is rejected due to a missing or invalid CSRF token, Laravel will return a 419 Page Expired error.

To debug:

  1. Ensure your form includes @csrf if using Blade.
  2. Verify the token is correctly passed in AJAX requests.
  3. If testing API routes, consider disabling CSRF for API endpoints (see Step 6).

Step 6: Disabling CSRF Protection for Specific Routes

If you have an API or webhook that does not require CSRF protection, you can exclude it in VerifyCsrfToken.php:

Path: app/Http/Middleware/VerifyCsrfToken.php

protected $except = [ '/api/*', // Excludes all API routes '/webhook/*' // Excludes specific webhook endpoints ];

Use this cautiously, as disabling CSRF can expose your application to security risks.

Step 7: Regenerating CSRF Token After User Logout

Laravel automatically regenerates the CSRF token after logout for security reasons. If you face issues with token mismatches, ensure your session is correctly refreshed after logging in or out.

Conclusion

  • CSRF protection is enabled by default in Laravel.
  • Use @csrf in forms.
  • Include CSRF tokens in AJAX requests.
  • Handle 419 errors by ensuring tokens are included.
  • Exclude API routes from CSRF protection only when necessary.

Would you like an example with Laravel controllers and routes? 🚀

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close