Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 11 - Disable CSRF for a route

I have a route that serves as a webhook endpoint that gets called by a remote service, but the calls that the service makes to the webhook always fail.

After some inspection of the service logs, I learned that the service is getting an HTTP error code 419.

I used to add exceptions inside the $except property of the App\Http\Middleware\VerifyCsrfToken middleware, However, I'm on Laravel 11 and I can't find this middleware anymore. What is the solution to this problem?

like image 969
Eyad Bereh Avatar asked Dec 11 '25 12:12

Eyad Bereh


2 Answers

Starting from Laravel 11, the VerifyCsrfToken middleware no longer exists within the application's skeleton.

Instead, you can specify which routes should bypass the CSRF verification process using the validateCsrfTokens() method. You can call this method inside the withMiddleware() method callback within your bootstrap/app.php file. For example:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        channels: __DIR__.'/../routes/channels.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->validateCsrfTokens(except: [
            'you-webhook-endpoint/action-name' // <-- exclude this route
        ]);
    })->create();

More information available at the documentation at: https://laravel.com/docs/11.x/csrf#csrf-excluding-uris

Update: You can also call the static except() method on the VerifyCsrfToken middleware class inside the boot() method of your AppServiceProvider class as following:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::except([
            'submit'
        ]);
    }
}
like image 104
Eyad Bereh Avatar answered Dec 13 '25 03:12

Eyad Bereh


I would like to quote the answer from Laravel's documentation:

You may also exclude specific routes by providing their URIs to the validateCsrfTokens method in your application's bootstrap/app.php file:

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ]);
});

Source: https://laravel.com/docs/11.x/csrf#preventing-csrf-requests

like image 32
John Doe Avatar answered Dec 13 '25 03:12

John Doe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!