Codeigniter 3.1.11 / Jquery (AJAX) doesnot pick up the value of csrf_cookie_name using $.cookie

Viewed 85

I have read several threads here on stackoverflow and other articles through google. I tried everything suggested but CSRF things are not working for me when I hit an AJAX request via Jquery.

Codeigniter Version: 3.1.11

JQuery Version: 2.1.4

JQuery Cookie Version: 1.4.1

config.php

$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] =  BASEPATH . 'cache/';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['cookie_prefix']    = '';
$config['cookie_domain']    = '';
$config['cookie_path']      = '/';
$config['cookie_secure']    = TRUE;
$config['cookie_httponly']  = TRUE;
$config['standardize_newlines'] = FALSE;
$config['global_xss_filtering'] = TRUE;
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'my_csrf_token';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
$config['compress_output'] = FALSE;
$config['time_reference'] = 'local';
$config['rewrite_short_tags'] = FALSE;
$config['proxy_ips'] = '';

JQuery Code which doesnt work

$.ajax({
    type: "post",
    url: "<?php echo base_url(); ?>" + "controllername/controllerfunction/parameter",
    data: {key1: val1, key2: val2, <?php echo $this->security->get_csrf_token_name();?> : $.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>") },
    success: function(res){
        if(res) {
            //do something
        }
    },
    error: function(res, status, error) {
        //do something
    }
});

Error I get in the network tab

The action you have requested is not allowed.

What works fine is replacing the data part of AJAX request

data: {key1: val1, key2: val2, <?php echo $this->security->get_csrf_token_name();?> : '<?php echo $this->security->get_csrf_hash();?>' },

But this shows the HASH VALUE in the source of my web page and also I cannot hit multiple AJAX requests from one page since CI will regenerate new hash on each POST request

PROBLEM 1:

How to get this $.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>" working?

PROBLEM 2: If I mark $config['csrf_regenerate'] = TRUE;, only 1 AJAX request works on one page, other buttons refuse to work, might be because CI has created a new hash after 1 execution, while the page still have old hash. So, if my problem 1 is solved, will problem 2 be automatically solved?


UPDATE: I figured out that setting $config['cookie_httponly']= FALSE; allows Jquery to fetch the cookie value.

Is it possible to keep this setting TRUE and still get Cookie info from JQuery AJAX?

1 Answers

Because you are using Codeigniter version 3.0, change this in config:

$config['csrf_regenerate'] = FALSE;

This working for me.

Related