CSRF (Cross-Site Request Forgery) protection in Laravel stops unauthorized or harmful requests from being carried out on behalf of authenticated users. It’s especially helpful to thwart attacks where an authenticated user is deceived into making an unintended request, leading to undesired actions or alterations in data.

Excluding routes from CSRF protection should be done carefully, as it opens those routes to CSRF attacks. Only exclude routes when you’re certain they’re secured by other means (like an API key or secure webhook endpoint validation) or if they’re not sensitive to the CSRF threat model.

You must have a Laravel 6 or higher version to execute this.

Sometimes we have to bypass certain routes for CSRF middleware in our Laravel application. From my experience, while working with the Twilio API, I needed to establish a callback URL using the POST method.

To exclude a route from CSRF protection in Laravel, you can use the $except property in the VerifyCsrfToken middleware. Follow the next steps –

Step 1: Find the VerifyCsrfToken middleware file in your Laravel project. You may find it in: app/Http/Middleware/VerifyCsrfToken.php

Step 2: Add the Route to the $except Array: Inside the VerifyCsrfToken middleware, you’ll see a $except property, which is an array of URIs that should be excluded from CSRF verification. Add the URI of the route you want to exclude here.

&lt?php

namespace App\Http\Middleware;

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

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'route-to-exclude', // Add your route here like  'sms/callback'
        'another-route/*',  // You can also use multiple routes like 'posts/store'
    ];
}

Step 3: Clear Config Cache (Optional): If your CSRF exclusion doesn’t seem to work, you may need to clear your configuration cache by using the command.

php artisan config:cache

This might be helpful for you. By excluding only necessary routes, you maintain security without adding barriers where CSRF tokens are impractical or redundant.

Share.
Leave A Reply

Exit mobile version