CSRF Token usage in Codeigniter 3.0 (PHP)

edit app/config.php

    


$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();//array('get-sub-postings-employee-list','get-searched-employees');
$csrf_pages = array('add-employees-posting');
if (isset($_SERVER["REQUEST_URI"])) {
    foreach ($csrf_pages as $csrf_page){
        if(stripos($_SERVER["REQUEST_URI"],$csrf_page) !== FALSE) {
            $config['csrf_protection'] = TRUE;
            break;
        }
    }
}
/*


now in views

add input field like this

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" class=
"csrfHash" value="<?php echo $this->security->get_csrf_hash();?>"/>

That's it now CSRF TOken is added to your form

For ajax functionality

access token form cookies HttpOnly false

var getCookies = function(){
            var pairs = document.cookie.split(";");
            var cookies = {};
            for (var i=0; i<pairs.length; i++){
                var pair = pairs[i].split("=");
                cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
            }
            return cookies;
        }
var myCookies = getCookies();
                    //myCookies.csrf_cookie_name; // "do not tell you"
                    $('.csrfHash').val(myCookies.csrf_cookie_name);


pass csrf cookie in data in ajax call and update the csrfToken in the input field in the response and your are ready to go

var data = {
                'searchText': search_text,
                'recordsPerPage': pagination.recordsPerPage,
                'pageNumber': pagination.currentPageNumber,
                'includePosting': pagination.includePosting,
                'id': pagination.selectedPostingId,
                [$('.csrfHash').attr('name')]:getCookies().csrf_cookie_name,
                'bat_id': <?php echo $this->session->userdata('userid'); ?>,
                //'id':current_posting.id
            };
            //alert('hi');
            //alert($('#csrfHash').val());
            $.ajax({
                url: "<?php echo base_url(); ?>search-posting",
                type: "POST",
                xhrFields: { withCredentials: true },
                data: data,
                success: function(response,data1,xhr) {
                    console.log(response);
                    console.log(xhr);
                    //console.log(xhr.getResponseHeader());
                    var myCookies = getCookies();
                    //myCookies.csrf_cookie_name; // "do not tell you"
                    $('.csrfHash').val(myCookies.csrf_cookie_name);
                    var obj = JSON.parse(response);
                    console.log(obj['postings']);
                    insertDataInPostingList2(obj['postings']);
                    pagination.totalRecords = obj['total_postings'];
                    pagination.totalFilteredRecords = obj['total_filtered_postings'];

                    pagination.paginate();
                }
            });




Comments