Search code examples
phplaravelcsrflaravel-middlewarelaravel-11

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?


Solution

  • 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'
            ]);
        }
    }