2

I am using cakePHP 4.2.3 On my home page I have a form and I want to submit this one with ajax, with cakePHP, we have to specify in the header of AJAX request the "X-CSRF-Token" and to get this one, I have to do this :

var csrfToken = <?= json_encode($this->request->getCookie('csrfToken')) ?>;

This work very fine, but on the first page load, I can't access to csrfToken cookie,I have to refresh the page again to access to the cookie.

So my AJAX request cannot be sent if visitor just arrived on my website without visiting other pages before.

I know that in cakePHP 3.X the csrfToken was stocked in session directly. Do you have a solution for my problem ?

Thank you for your help

Best regards,

Loic

LoickMEYER
  • 50
  • 2
  • 14

1 Answers1

1

If at all, you would read the value from the response cookie, that is the cookie that is being set by your application, not from the request cookie, which is the cookie sent to your application by the user.

However in your application you better stay agnostic, and do it as shown in the docs, read the token from the csrfToken request attribute that is being set by your application:

$this->request->getAttribute('csrfToken')

See also

ndm
  • 59,784
  • 9
  • 71
  • 110
  • Thank you for the help, it work, but why in my debug bar, when I open the "Request" menu I don't see "csrfToken" in the list of attribute ? – LoickMEYER Mar 11 '21 at 22:41
  • 1
    @LoickMEYER I don't think debug kit will show any attributes other than the routing parameters. – ndm Mar 11 '21 at 22:57