0

I have spent nearly 2 days trying to solve this CSRF Token Mismatch issue.

I have an app running on laravel 4.2 and it has no issues with Ajax calls. I have migrated the site to Laravel 6 but I am having issues with Ajax calls. I checked the site source code and it has _token and so does the Ajax request (X-CSRF-Token) in the request header. Both of them match.

        $.ajaxSetup({
            headers: {
                'X-CSRF-Token': $('meta[name="_token"]').attr('content')
            }
        });

I have setup the ajax header to add token in each ajax call.

When inspecting the problem, in the VerifyCsrfToken.php middleware, I noticed that the 2 tokens that are compared did not match.

        return is_string($request->session()->token()) &&
               is_string($token) &&
               hash_equals($request->session()->token(), $token);

I checked the session files in the storage and noticed that there were multiple sessions files created, but each of them had different token value. However, when compared to the 4.2 code, all the tokens in session files were the same.

I do not have much knowledge on how these sessions files work.

I am wondering whether each request session should store the token different? Am I not storing the Cookie correctly or is there something different between version 4.2 and version 6.

Please any help is much appreciated.

bodi87
  • 501
  • 1
  • 6
  • 18
  • X-CSRF-Token needs to be all capital letters: X-CSRF-TOKEN – lewis4u Jul 09 '20 at 18:49
  • I tried this but still it says token mismatch – bodi87 Jul 09 '20 at 19:09
  • Add this on ajax `data`, not `headers`, hope this works `"_token": "{{ csrf_token() }}"`, example : `data: { "_token": "{{ csrf_token() }}", "id": id, "name:name" }` – STA Jul 09 '20 at 19:27
  • I tried that but no luck – bodi87 Jul 09 '20 at 19:37
  • Use axios, there's a reason it is a default in Laravel applications. You appear to be running into some of the CORS restrictions securing your application from CSRF forgeries. You are actually missing additional header info. See line 6 here for instance [https://github.com/laravel/laravel/blob/6.x/resources/js/bootstrap.js](https://github.com/laravel/laravel/blob/6.x/resources/js/bootstrap.js) – Azeame Jul 10 '20 at 01:05

0 Answers0