简体   繁体   中英

CSRF Token Valid on First Submit in Ajax - Codeigniter

Below is my code and how i submit my data using the Ajax. On first submit, the data is posted successfully, however, when i try again, it fails which i suspect is from an invalid csrf since a new token may be generated. How can i solve this problem ?

  $('#icon').on('click', '#test', function() {


                       var ids = $(this).data('id');
                    var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>',
                       csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
                   var dataJson = { [csrfName]: csrfHash, ids: ids };

                    $.ajax({
                      url: '<?php echo base_url('client/data'); ?>',
                     type: 'POST',
                     data: dataJson,

                    }).done(function (result) {

                     });
                     });

I have same problem and i solve this by refreshing csrf token. New csrf token get in ajax response form server and replace it old token which is store in form hidden field and when you submit again use the new token.It solve my problem hopes your problem also fixed by doing this, for more use this link https://codeigniter.com/user_guide/libraries/security.html

The solution that worked for me when $config['csrf_regenerate'] = TRUE is that for subsequent ajax post when CSRF is enabled for every request is to make a GET request in AJAX Success when request fails because token has expired. Then have a hidden field that continue to be updated with latest token and if at the time of making request it has expired you make a GET REQUEST to fetch latest TOKEN and then evoke click event on function that submits form or function making POST request which means the function has to be passed "this" or ID as part of parameter.This makes the user not to realize the process of renewing token in the background

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM