Skip to content

AJAX + CSRF Protection in Codeigniter ?

Last updated on May 6, 2018

Codeigniter 2.0 adds an important security feature to prevent CSRF (Cross Site Request Forgery) attacks. Even better, the feature is automatically added to your forms(if you enable CSRF in Config, and if you use CI form Helper).

You might like this post –
How to Enable CSRF (Cross Site Request Forgery) in CodeIgniter

How CSRF Protection Work in CodeIgniter?

if you visit page after enabling CSRF Protection, the CI form helper adds a hidden input element to the from with randomly generated hash String as a value (input field default name is csrf_test_name, you can change it in config file) and at the same time CI sets a cookie with same hash(the default Cookie name is csrf_cookie_name, as usual, you can change it in config). When the form is submitted by the user that hidden input is compared with the cookie value. If they do not match the request is rejected before it ever reaches your controller method(action).

This way you can protect your website from outside form submissions from the malicious users.

if you are not using CI’s form helper , hidden input field will not generate automatically you have to set it manually as shown below, past this in side your form.


Why my AJAX functions were returning 500 Internal Server Errors With CSRF

Because your CSRF validation is field, in order to fix this problem you have to pass your CSRF hidden input value with in your ajax request.

you can get hash value and pass it with JQuery something like this:

 // get the hash 
   var csrf_test_name = $("input[name=csrf_test_name]").val();


// send request with hash
$.ajax({
  type: "POST",
  url: url,
  data: { 'csrf_test_name' : csrf_test_name,'name' : 'arjun'  },
  success: success,
  dataType: dataType
});

What if your numerous places to add ?

For this i am gonna use $.ajaxSetup . All post data from Ajax functions throughout your application will be merged with the data set by $.ajaxSetup.

Here is the Example :

$(function($) {

    // this script needs to be loaded on every page where an ajax POST may happen
    $.ajaxSetup({
        data: {
            'security->get_csrf_token_name(); ?>' : 'security->get_csrf_hash(); ?>'
        }
    });


  // now write your ajax script 

});
3.5 2 votes
Article Rating
Subscribe
Notify of
guest

13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments