CakePHP ajax CSRF token mismatch

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

I am making an ajax request with Csrf component load in my AppController

However I get the error {"message":"CSRF token mismatch.","url":"\/module_slides\/loadDeck.json","code":403}

Here is the request header

POST /module_slides/loadDeck.json HTTP/1.1 Host: www.hotelieracademy.com Connection: keep-alive Content-Length: 18 Origin: https://www.hotelieracademy.com X-XSRF-TOKEN: 3d3901b1de9c5182dce2877c9e1d9db36cdf46a6 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Accept: application/json, text/javascript, */*; q=0.01 X-Requested-With: XMLHttpRequest Referer: https://www.hotelieracademy.com/courses_employees/player/70 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.8 Cookie: csrfToken=3d3901b1de9c5182dce2877c9e1d9db36cdf46a6; CAKEPHP=3n6lpi94hrdgsg8mv4fsnp1m30; _ga=GA1.2.2010364689.1424741587 

My ajax code

$.ajax({             url: '/module_slides/loadDeck.json',             type: 'POST',             headers: { 'X-XSRF-TOKEN' : this.csrfToken },             beforeSend: function (xhr) {                 xhr.setRequestHeader('X-CSRF-Token', this.csrfToken);             },             dataType: 'json',             data: { 

I have left the beforeSend: as suggest by another post but does not seem to alter the header so I added headers:

I use a hidden input to get the CsfR token to use in my js code

<input id="csrfToken" type="hidden" value="<?= $this->request->params['_csrfToken'] ?>"> 

回答1:

I've met the same problem. Probably, this is the answer to add "_csrfToken":"xxxxxxx" to data{}.

$.ajax({         url: '/module_slides/loadDeck.json',         type: 'POST',         headers: { 'X-XSRF-TOKEN' : this.csrfToken },         beforeSend: function (xhr) {             xhr.setRequestHeader('X-CSRF-Token', this.csrfToken);         },         dataType: 'json',         data: {            "_csrfToken":"3d3901b1de9c5182dce2877c9e1d9db36cdf46a6"         } 

This is my blog.but it's Japanese Only. http://www.tsuji75.com/?p=62



回答2:

Here is my solution.
For the CSRF token, I am creating an empty cakephp form and it provides the CSRF token. Also, I do not unlock any action. instead I do unlock fields.

Ref: https://book.cakephp.org/3.0/en/controllers/components/security.html

here is my working example.

Scenario: Ajax call to add an event was failing due to cakephp 3 CSRF token mismatch issue.

Solution:

  1. I have created an empty form in the view so it can provide CSRF token for my form and then attached the required input fields before the ajax. In the form itself, I unlocked the hidden fields. This way I do not disturb CSRF component. In VIEW

    <?= $this->Form->create(false, [     'id' => "ajaxForm",                         'url' => ['controller' => 'XYZ', 'action' => 'add'],                         'class'=> "addUpdateDeleteEventForm"                         ] );                         $eventdata = [];                         ?>                             <?= $this->Form->unlockField('id'); ?>                             <?= $this->Form->unlockField('start'); ?>                             <?= $this->Form->unlockField('end'); ?>                             <?= $this->Form->unlockField('title'); ?>                         <?= $this->Form->button('Submit Form', ['type' => 'submit']);?>                         <?= $this->Form->end(); ?> 
  2. Ajax:

            var id = $("<input>")         .attr("type", "hidden")         .attr("name", "id").val(id);     var titleField = $("<input>")         .attr("type", "hidden")         .attr("name", "title").val(title);     var startTime = $("<input>")         .attr("type", "hidden")         .attr("name", "start").val(start);     var endTime = $("<input>")         .attr("type", "hidden")         .attr("name", "end").val(end);     $('#ajaxForm').append(id);     $('#ajaxForm').append(titleField);     $('#ajaxForm').append(startTime);     $('#ajaxForm').append(endTime);       var ajaxdata = $("#ajaxForm").serializeArray();      $.ajax({         url:$("#ajaxForm").attr("action"),         type:"POST",         data:ajaxdata,         dataType: "json",         success:function(response)         {             toastr.success(response.message, response.title);             calendar.fullCalendar("removeEvents");             calendar.fullCalendar("refetchEvents");         },         error: function(response)         {             toastr.error(response.message, response.title);         }     }); 

Hope this helps.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!