Enabling CSRF Protection in CodeIgniter for AJAX calls
If you use CodeIgniter (CI) like me, you’ve probably read/heard about the CSRF protection that comes built into this great framework. I typically kept ajax functionality (form submissions in this case) to a minimum as I wanted to focus more on development and finishing a project than prettying it up with ‘Web 2.0’ stuff.
Well in a couple of my last projects I’ve ran smack into CSRF protection and how it impacts AJAX (as well as many other things like Paypal payment gateway responses, etc).
If you found this page when searching for Codeigniter CSRF Ajax, then you’re in luck, as here is the easiest way to add CSRF protection to your ajax calls:
$.ajax({ type: 'POST', url: '/action/fetch_more_blog_posts', data: { type: 'news', limit: limit, offset: offset, <?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>' }, success: function(data) { $(data).appendTo('#more-entries'); $('#older-posts').slideDown(); offset += limit; } });
The magic really here is the following entry in the data I am sending back to my controller:
<?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'
The `get_csrf_token_name()` gets you your token name from the security class (first set in your config), and the `get_csrf_hash();` simply outputs the secure hash from the security class. Simple enough.
If you have timeout issues (say your ajax page sits too long, you may increase the token a bit, test for best fit).