craftcms / cms

Build bespoke content experiences with Craft.
https://craftcms.com
Other
3.26k stars 633 forks source link

[4.x]: CSRF not working with AJAX requests #12359

Closed TomDeSmet closed 1 year ago

TomDeSmet commented 1 year ago

What happened?

Description

Whenever I do an AJAX POST request with CSRF enabled, it returns a 400 Bad request error. I'm using fetch() in Vue 3 and I tried all following:

  1. Using the CSRF token generated in Twig with {{ craft.app.request.csrfToken }}
  2. Sending a request to session-info and use the CSRF Token returned by it.
  3. Sending the CSRF token as a header 'X-CSRF-Token': sessionCsrfToken
  4. Sending the CSRF token in FormData 'CRAFT_CSRF_TOKEN', sessionCsrfToken

The thing I don't understand is that the CSRF token in my Cookies is always different than the ones Twig generates or Session Info returns. And if I understand correctly, those should be the same?

I tried with update-cart and with a custom module controller. Both don't seem to work. What am I missing here?

Craft CMS version

5.3.3

PHP version

8.1

Operating system and version

MacOS Big Sur

Database type and version

MySQL

Image driver and version

No response

Installed plugins and versions

-

TomDeSmet commented 1 year ago

My own fault, I was adding the wrong properties for credentials to my request.