Shu Pesmerga
Shu Pesmerga

Reputation: 145

CSRF Token mismatch in cookies and html

How can i retrieve the CSRF Token 'properly'?

I am trying to use Axios to login in my Vue SPA.

I changed everything to Vue component except for the Routes Auth::routes(); generated by php artisan ui:auth. Therefore, I can no longer use @csrf on my forms and have to send the csrf token through the header of axios. I've tried almost everything for 2 days now until I notice that the XSRF TOKEN given to my cookies by Laravel is different from what I'm getting in my HTML... Please refer to the photos below.

This is coming from the developer tools.

enter image description here enter image description here

app.blade.php

I added this so i can set retrieve the CSRF token and attach it to the axios headers.

enter image description here

Upon console.log(), I see a different token. enter image description here

The token i get when I console.log() : o3nQRW6IqiKdNGOdiHc59pYXXD3sBw8YfbpCPvf7

enter image description here

Why don't just get the CSRF Token from the cookie then using document.cookie?, same thing. It doesn't match whenever I console.log().

This is definitely the reason why whatever I do, i always got a 419 error CSRF token mismatch. What could be causing this?

Note: I'm only using the Auth::routes() in the api.php file. Nothing in web.php. Strangely, I was able to register a user ONCE but never again due to the same issue.

Upvotes: 1

Views: 2469

Answers (1)

Robin Dirksen
Robin Dirksen

Reputation: 3422

It's difficult to say at this moment, but hopefully this helps:


Is your SPA outside of your Laravel application? Then I suggest to use the new Laravel Airlock package that handles the CSRF token for you. More information can be found here: https://laravel.com/docs/7.x/airlock

Laravel Airlock is renamed to Sanctum: https://blog.laravel.com/airlock-renamed-to-sanctum

If your SPA is inside your Laravel app, take a look to your axios configuration if it uses the X-CSRF-Token in the header. More information can be found here: https://laravel.com/docs/6.x/csrf#csrf-x-csrf-token

Upvotes: 1

Related Questions