Welcome Guest, Not a member yet? Register   Sign In
CodeIgniter CSRF Protection With Ajax
#1

Hi! CI Forum Members,

I am developing an application using CI. Most of My forms use Ajax to push data to the server. I am currently working on adding CSRF protection to all my forms.

I read this note from the documentation in CSRF section that:
Quote:Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security,
and so, I choose to regenerate csrf_token.

Using Ajax, the page is not refreshed and thus resulting into the page having invalid token for further submissions which will always fail. 

I have decided to follow the advice from one of the website/blog to read csrf_token from the cookie using javascript cookie library, and pass it  along with every post request.

Here is code snippet:

PHP Code:
$("#selector").click(function () {
 
   e.preventDefault();
 
   var form_data = {
 
       cat_name: $('#something').val(),
 
       csrf_token_name: $.cookie("csrf_cookie_name")
 
   };

 
   $.ajax({
 
       type"POST",
 
       urlSITE_URL "controller",
 
       dataform_data,
 
       success: function(data) {
 
           alert('it worked');
 
       }
 
   });
}); 
 
Is this implementation safe to use for csrf protection? What are the risks if any?

Any help or recommendation is appreciated!
Reply


Messages In This Thread
CodeIgniter CSRF Protection With Ajax - by SammieL - 09-15-2016, 02:54 AM



Theme © iAndrew 2016 - Forum software by © MyBB