Sling Academy
Home/PHP/How to disable/enable CSRF protection in Laravel

How to disable/enable CSRF protection in Laravel

Last updated: January 15, 2024

Introduction

Cross-Site Request Forgery (CSRF) is a common security vulnerability in web applications. Laravel, a popular PHP framework, includes CSRF protection by default to ensure the security of applications. However, there are scenarios in which a developer might need to selectively disable or enable CSRF protection. In this tutorial, we will explore how to do so in a Laravel application, with a series of code examples from basic to advanced uses.

Understanding CSRF Protection in Laravel

Laravel includes middleware that automatically checks for a CSRF token in each POST, PUT, PATCH, or DELETE request. The token ensures that the request originates from the same application and prevents unauthorized actions. This middleware is applied globally, but Laravel also provides ways to manage its behavior.

<!-- Example of a CSRF field in a Laravel form -->
 <form method="POST" action="{{ route('example.route') }}">
     @csrf
     <!-- Other form fields -->
 </form>

Disabling CSRF Protection in Laravel

To disable CSRF protection, you may modify the VerifyCsrfToken middleware. Start with the basic exclusion of routes by editing the $except property.

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    protected $except = [
        'route/to/exclude',
        'another/route/to/exclude',
    ];
}

In this configuration, the routes specified in the $except array won’t be checked for a CSRF token.

Disabling CSRF Protection for API Routes

APIs typically use tokens for authentication and do not require CSRF protection. You can apply middleware to group your API routes accordingly to disable CSRF checks.

// In your routes file (e.g., web.php or api.php)
Route::group(['middleware' => ['api']], function () {
    // Your API routes
});

// In the RouteServiceProvider class
protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}

Enabling CSRF Protection on Specific Routes

If you’ve disabled CSRF protection globally, you may want to re-enable it for certain routes. This is less common but can be done by applying the web middleware.

Route::post('protected/route', function () {
     // Route logic
 })->middleware('web');

By applying the web middleware to this route, you are including the CSRF protection.

Testing CSRF Protection

When making changes to CSRF protection settings, it’s important to test them thoroughly. Below is an example of how to write a feature test for a route with CSRF protection disabled.

public function disable_test_route_without_middleware()
 {
     $response = $this->withoutMiddleware()->post('/route/to/test', []);
     $response->assertStatus(200);
 }

This test confirms that the route is accessible without the CSRF middleware applied.

Conclusion

In this tutorial, we covered the steps to enable and disable CSRF protection in a Laravel application. As you’ve learned, managing CSRF protection is crucial for both the security and flexibility of your application. Remember to thoroughly test any changes to CSRF settings to ensure your application remains secure.

Next Article: How to Enable/Disable Blade Template Caching in Laravel

Previous Article: Laravel: How to render JSON data in Blade templates

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array