Laravel CSRF on second (third, etc.) ajax request

278 Views Asked by At

In a laravel application, I have a form which I submit by javascript. I added the {{ csrf_field() }} to the form and I am using the VerifyCsrfToken middleware.

The first request works fine and as expected. But if I don't refresh the page and resend the same form (for example because of form field validation errors), I get a 419 error on my request. I think its because the _token is the same in both requests and somekind of invalidated on the first request.

Is there a way, to prevent a csrf token to be invalidated on a request, so that I can reuse it as long as I need it?

1

There are 1 best solutions below

2
On

If you're not using the Axios HTTP library (it's included in bootstrap.js file) you will need to manualy update the CSRF token from the received cookies of the previous request.

the Axios HTTP library provided in the resources/js/bootstrap.js file automatically sends an X-XSRF-TOKEN header using the value of the encrypted XSRF-TOKEN cookie. If you are not using this library, you will need to manually configure this behavior for your application.

--EDIT-- Since your pages are cached and static. either lose the caching or lose the CSRF in app\Http\Kernel.php comment the line for the middleware VerifyCsrfToken

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, <--- THIS ONE
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\CheckBlocked::class,
    ],

];