Laravel Disable CSRF Protection on Specific Routes

Published on September 30, 2019 42 sec read

CSRF stands for Cross-Site Request Forgery. It is also known as XSRF, Sea Surf, and Session Riding. CSRF is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated.

Laravel verifies CSRF using VerifyCsrfToken middleware. Here’s the location of the middleware: Illuminate\Foundation\Http\Middleware\VerifyCsrfToke. This middleware gets executed on every HTTP request.

Disable CSRF Protection

To disable CSRF protection, navigate to app\Http\Middleware and open VerifyCsrfToken.php file. We need to add the routes in protected $except = []; array.

Example: I’m going to disable CSRF protection on three routes. The routes are:

routes\web.php
Route::post('route1', '[email protected]');
Route::post('route2', '[email protected]');
Route::post('route3', '[email protected]');

Let’s disable protection on these routes:

app\Http\Middleware\VerifyCsrfToken.php
<?php

namespace App\Http\Middleware;

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

class VerifyCsrfToken extends Middleware
{
    /**
     * Indicates whether the XSRF-TOKEN cookie should be set on the response.
     *
     * @var bool
     */
    protected $addHttpCookie = true;

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'route1', 'route2', 'route3',
    ];
}
The tutorial is over. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *