Laravel- VerifyCsrfToken exclude not working

Viewed 1002

I'm having an issue with excluding a route from verifying CSRF token.

I'm trying to exclude all requests on an endpoint which I call mydomain.com/example so I do like this in the VerifyCsrfToken.php file.

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 = [
        'example/*',
    ];
}

But it does not solve the issue. If I do this in the app/Http/Kernel.php file everything works as it should.

Does anyone know why I can't exclude specific routes?

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            //\App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Barryvdh\Cors\HandleCors::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
2 Answers

You're excluding every route AFTER "/example" by using the wildcard and the middleware isn't registered in the kernel and therefore not even running

protected $except = [
    '/example'
];

And don't forget to uncomment the middleware

'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    // \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class, // <--- HERE
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Barryvdh\Cors\HandleCors::class,
],

Use

protected $except = [
    '/example/*',
];

Do not forget the slash / at the beginning.

Related