How to disable/enable CSRF protection in Laravel

Updated: January 15, 2024 By: Guest Contributor Post a comment

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.