codeigniter Securing your web application CSRF Prevention


Example

CSRF stands for cross-site request forgery. You can prevent this attack by enabling an option in the application/config/config.php file as shown below.

$config['csrf_protection'] = TRUE;

When you create a form using the form_open() function, it will automatically insert a CSRF token in a hidden field. You can also manually add the CSRF token using the get_csrf_token_name() and get_csrf_hash() function. As their names suggest, the get_csrf_token_name() function will return the name of the CSRF token, while get_csrf_hash() will return the hash.

The CSRF token can be regenerated every time for submission or you can also keep it the same throughout the life of the CSRF cookie. Setting the configuration option ‘csrf_regenerate’ will force regeneration of the token as shown below.

$config['csrf_regenerate'] = TRUE;

You can whitelist URLs from CSRF protection by setting matches for them in the configuration array using the key ‘csrf_exclude_uris’ as shown below. You can also use regular expressions.

$config['csrf_exclude_uris'] = array('api/person/add');