John
John

Reputation: 750

CSRF and Ajax issue in CodeIgniter 3

I am using CodeIgniter3 in my application and some of the forms use ajax. I have set csrf_regenerate = TRUE. Initially I had the problem of passing csrf tokens in successive ajax calls(for populating combo box) and I have resolved it.

I have a page where I update the CSRFToken:

<script type="text/javascript" language="javascript">

var csfrData; 
csfrTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>';
csfrHash = '<?php echo $this->security->get_csrf_hash(); ?>';

setCSRF(csfrTokenName, csfrHash);

function setCSRF(name, value) {
    csfrData = {}; // Reset csrfData to an empty array
    csfrData[name] = value;     
}
</script>

Then for ajax calls, I do the following:

$('#department_id').change(function() {

var department_id=$("#department_id").val();
var domain=$("#domain").val(); 

$.ajax({        
    'type': "POST",
            url: domain + "index.php/project/get_scheme",
            data: {department_id: department_id, csrf_test_name: csfrData.csrf_test_name},
            dataType: 'json',
            success: 
        function(j){

              setCSRF(j.csrfTokenName, j.csrfTokenHash);
              if(j.schemes.length >= 2) {
                var options = '';
                for (var i = 0; i <= (j.schemes.length-1); i++) {
                        options += '<option value="' + j.schemes[i].id + '">' + j.schemes[i].name + '</option>';
                }
                $("#scheme_id").html(options);
                $('#scheme_id option:first').prop('selected', 'selected');
              }                          
        }
      });

   });

This way all the combo boxes are populated. But when i finally submit the form,the following error comes up:

The action you have requested is not allowed.

When I checked using Burpsuite,I found that this time the values of csrf_token_name and csrf_cookie are not matching and hence the error. I am not able to figure out why this is happening. Any guidance will be welcome.

Upvotes: 1

Views: 875

Answers (1)

John
John

Reputation: 750

I have resolved the issue. I am posting it here so that it helps people looking for the answer in future. I didn't realize an important point that though the csrf token is being changed with every ajax request, the form has still got the old token. So during form submission, the old token does not match with token at server.

In the last call, I have removed the old token from the hidden field and replace it with the latest token. Then the form got submitted successfully.

$('input:hidden[name=csrf_test_name]').val('');
$('input:hidden[name=csrf_test_name]').val(j.csrfTokenHash);    

Thank you all.

Upvotes: 1

Related Questions