Protecting your CodeIgniter application from Cross-site request forgery (CSRF or XSRF) attacks is pretty easy thanks to the built-in support. Once CSRF protection is enabled in the config file, you can use the form helper or custom code to protect your forms and AJAX calls from CSRF. The CodeIgniter framework will automatically protect forms or calls that make POST requests once protection is enabled – here’s how to update your application.
Enable CSRF Protection
To enable CSRF protection in your CodeIgniter application, edit the
application/config/config.php file and look for
$config['csrf_protection']. Change the setting to
TRUE (if it isn’t already) to enable protection. If you then test a form or AJAX call in your application, the request will fail showing a generic error:
This means that CSRF protection is working, and we now need to update the forms to add a CSRF token to the POST data.
Updating forms with CSRF tokens
The easiest way to update your forms is to use the Form Helper. Load the form helper manually (in your controller) or add it to the
application/config/autoload.php file and call
echo form_open('login'); (the first parameter is the form
action, and the second parameter is an array of attributes):
form_open() will automatically add in a new field into the form with a randomly generated token used to prevent CSRF.
If you don’t want to use
form_open(), you can add it to your form manually with:
After updating your form, test the code by POSTing some data and the request should now go through as normal. To test it further, edit the value of the CSRF input (e.g. using Chrome), then submit the form again. Changing the CSRF token will result in the above error message as CodeIgniter has detected a CSRF attack.
Updating AJAX Calls
AJAX calls that POST data will also fail if the CSRF token is not added. CodeIgnitor will return a Error
500 (Internal Server Error) for failed AJAX calls that do not contain a valid CSRF token field. There are a number of ways this can be achieved, depending on how you’ve coded your applications. I’ve included two different examples below:
Using Form Serialization
Once the changes have been made, test the AJAX call to see if the request is posted correctly and a valid response is received.