CSRF token mismatch in cakephp3.6.13

need some help

Already checked using
in ctp js section
beforeSend: function (xhr) { // Handle csrf errors
xhr.setRequestHeader(‘X-CSRF-Token’, <?=$this->request->getParam('_csrfToken');?>);
},
or
beforeSend: function (xhr) { // Handle csrf errors
xhr.setRequestHeader(‘X-CSRF-Token’, $(’[name="_csrfToken"]’).val());
},

in cotroller
$this->loadComponent(‘Csrf’);

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
     $this->getEventManager()->off($this->Csrf);

}

Could you verify it sends the token in the header with the request?

Already checked in network mode
Csrf parameters present.

How to verify in header??

Well… in the network monitor you literally have a tab “Headers” :stuck_out_tongue:

Then it should be in the “Request Headers”

Not getting X-CSRF-Token in header.
how to send X-CSRF-Token?
i’m already add this in ajax.

I mostly use jQuery to handle my AJAX calls so it might vary for you depending on what you use:

$.ajax({
  headers: {
    'X-CSRF-Token': <?= json_encode($this->request->getParam('_csrfToken')); ?>
  }
  // ... My other stuff
});

I think with plain javascript (so no jQuery), it’d look something like this:

var request = new XMLHttpRequest();
request.setRequestHeader(‘X-CSRF-Token’, <?=$this->request->getParam('_csrfToken');?>);

request.send(); // Or whatever one does to send it
1 Like

Thanks for your quick reply.
This is working.
Thank you very much.:slightly_smiling_face::slightly_smiling_face:

1 Like

I have one more question, we need to load “$this->loadComponent(‘Csrf’);” in controller??

You shouldn’t have to afaik

If don’t load this return ''false "

As far as I can see, I only have the CsrfMiddleware enabled in my site and it works just fine:

1 Like

You need the component or the middleware to be loaded, but not both.

1 Like