Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel + Vue.js (axios) - CSRF token mismatch

I have problem with csrf token in Laravel. Sometimes request POST (via axios) returns 419 code "CSRF token mismatch" but request header contain CSRF and XSRF tokens. Interestingly, it's not happend in incognito mode.

enter image description here

App.blade:

<meta name="csrf-token" content="{{ csrf_token() }}">

bootstrap.js:

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';


let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

Kernel.php:

    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,
            \App\Http\Middleware\Localization::class,
        ],

I tried to clear cache and config with no results. Any ideas how to fix it?

like image 506
serpentow Avatar asked Dec 22 '19 22:12

serpentow


2 Answers

I encountered this issue. The cause was axios headers not being set. Setting them on the axis object within the component also did not resolve the issue. Setting the headers after the object is defined resolved the issue for me.

In your blade view add the following:

<script>window.Laravel = {csrfToken: '{{ csrf_token() }}'}</script>

In your bootstrap.js file, after declaring window.axios = require('axios'); add the following:

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
like image 176
Kevin Lynch Avatar answered Oct 17 '22 02:10

Kevin Lynch


Sometimes?! It sounds like a expired token.

When you're working in incognito tabs, you have a fresh token.

Try location.reload() when you're getting 419 error code and everything goes well.

like image 1
Khalil Laleh Avatar answered Oct 17 '22 00:10

Khalil Laleh