codeigniter
  1. codeigniter-csrf

CSRF (Cross-Site Request Forgery) in CodeIgniter

Cross-Site Request Forgery (CSRF) is a security vulnerability that can be exploited to carry out unauthorized actions in a web application. In CodeIgniter, CSRF protection is built-in as a security feature to prevent such attacks.

Syntax

CSRF protection is enabled by default in CodeIgniter. To ensure that CSRF protection is enabled, navigate to the application/config/config.php file and ensure that the $config['csrf_protection'] setting is set to TRUE.

Example

To enable CSRF protection in your CodeIgniter application:

  1. Set the $config['csrf_protection'] setting to TRUE in the application/config/config.php file.
  2. In your forms, add a hidden input field with the name csrf_test_name and its value set to the result of the csrf_hash() function.
<input type="hidden" name="csrf_test_name" value="<?php echo csrf_hash(); ?>" />
  1. In your controller methods that handle form submissions, use the verify_csrf() function to verify that the CSRF token submitted with the form matches the CSRF token generated by CodeIgniter.
if ($this->input->method() === 'post' && ! $this->security->verify_csrf()) {
    // Handle CSRF attack
}

Explanation

In the above example, the csrf_hash() function is used to generate a unique CSRF token, which is then added as a hidden input field to the form. When the form is submitted, the CSRF token is verified using the verify_csrf() function in the controller method. If the CSRF token does not match the one generated by CodeIgniter, a CSRF attack is likely underway and can be handled accordingly.

Use

CSRF protection is a crucial security feature in web applications. By enabling CSRF protection in CodeIgniter, you can prevent unauthorized actions from being carried out through your application.

Important Points

  • CSRF protection is enabled by default in CodeIgniter.
  • When using CodeIgniter's CSRF protection, a unique token must be generated for each form submission.
  • In your controller methods that handle form submissions, use the verify_csrf() function to verify the CSRF token.

Summary

Cross-Site Request Forgery (CSRF) is a security vulnerability that can be exploited to carry out unauthorized actions in a web application. CodeIgniter comes with built-in CSRF protection, which is a crucial security feature in web applications. CSRF protection is enabled by default in CodeIgniter, and uses a unique token to verify form submissions. Using CodeIgniter's CSRF protection is a simple but important step in protecting your application from security vulnerabilities.

Published on: