Milind Daraniya

How to Disable CSRF Token in Laravel 10

Published August 2nd, 2023 24 min read

By default, Laravel provides built-in CSRF (Cross-Site Request Forgery) protection, which helps prevent malicious attacks. However, in some cases, you may need to disable CSRF protection for specific routes or APIs. In this tutorial, we'll guide you through the process of disabling the CSRF token in Laravel 10. Let's get started!

Disabling CSRF Protection for Specific Routes 
To disable CSRF protection for specific routes in Laravel, you can utilize the except property in the VerifyCsrfToken middleware. Open the app/Http/Middleware/VerifyCsrfToken.php file and update the except property as shown in the following example:

protected $except = [
    'example/route1',
    'example/route2',
];

Replace 'example/route1' and 'example/route2' with the actual routes where you want to disable CSRF protection. This ensures that CSRF protection is bypassed for these routes.

Disabling CSRF Protection for APIs 
When working with API routes, you can disable CSRF protection for the entire API by removing the VerifyCsrfToken middleware from the App\Http\Kernel class. Open the app/Http/Kernel.php file and remove 'VerifyCsrfToken' from the api middleware group as shown in the following example:

protected $middlewareGroups = [
    'web' => [
        // Other middlewares
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        // Other middlewares
        // Remove the VerifyCsrfToken middleware
    ],
];

By removing the VerifyCsrfToken middleware from the api middleware group, CSRF protection is disabled for all API routes.

Disabling CSRF Protection for a Single Route 
If you want to disable CSRF protection for a specific route, you can add the withoutMiddleware method to the route definition. For example:

Route::post('/example', [ExampleController::class, 'store'])
    ->withoutMiddleware([\App\Http\Middleware\VerifyCsrfToken::class]);

By calling withoutMiddleware and passing the VerifyCsrfToken middleware, CSRF protection is disabled for this particular route.

Disabling CSRF protection should only be done with caution and for specific use cases where you are confident that the necessary security measures are in place. CSRF protection is a crucial security feature, and disabling it without proper justification can expose your application to potential risks.

Stay secure! 🔒🌐