Summer Sale! All accounts are 50% off this week.

laravolt's avatar

Laravel 8 - CSRF mismatch with axios

await axios.post('/test', { an: 123 });

Here's what axios is sending in the post request:

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 10
Content-Type: application/json;charset=UTF-8
Cookie: Cookie: remember_web_xxx=xxx; XSRF-TOKEN=xxx; xxx_session=xxx
Host: 127.0.0.1
Origin: http://127.0.0.1
Referer: http://127.0.0.1/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: xxx
X-Requested-With: XMLHttpRequest
X-XSRF-TOKEN: xxx

but the server replies with:

"message": "CSRF token mismatch.",

I've removed any other csrf_token calls I had, what else could be the issue?

0 likes
7 replies
tisuchi's avatar

@laravolt according to the doc, laravel will automatically add csrf for axios.

Laravel stores the current CSRF token in an encrypted XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN request header. This cookie is primarily sent as a convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN header on same-origin requests.

Ref: https://laravel.com/docs/8.x/csrf#csrf-x-xsrf-token

laravolt's avatar

I know it adds csrf, that's why I picked axios, but it still throws this error.

laravolt's avatar

I assume it does not due to the error, but which tokens shall I compare?

laravolt's avatar

I manually added a X-CSRF-TOKEN header to the request with what the meta tag says (added the tag back) - it still mismatches.

laravolt's avatar

Just checked in the csrf middleware, indeed, the frontend sends another csrf than laravel checks against - but why?.. the same issue happens with @csrf elements

laravolt's avatar
laravolt
OP
Best Answer
Level 1

Same issue as 1 year ago, if you change your user model to be uuid() you need to change your session migration too:

$table->foreignId('user_id')->nullable()->index();

to

$table->uuid('user_id')->nullable()->index();

Please or to participate in this conversation.