Secure Your CodeIgniter Application using CSRF Token

October 27, 2014

In this tutorial, we will learn how to make our website more secure & protect from CSRF when we are using CodeIgniter web application framework. We thanks CodeIgniter team who giving in built support Cross Site Rquest Forgery (CSRF or XSRF).

To enable CSRF protection CodeIgniter Framework will automatically protect forms or AJAX calls from CSRF when we use form helper and in custom form, we need to call CSRF token name & it’s value in hidden input field and send with POST requests.

Enable CSRF in Config file

To enable CSRF protection we need to modify config file of CodeIgniter Framework. We just need to change TURE instead of FALSE in our application/config/config.php file for example: $config[‘csrf_protection’] = TRUE;

After changing our web application is secure with CSRF protection. But if we used custom form instead of CodeIgniter form helper the POST request will fail and showing following error:

csrf_error_encountered

It means our CSRF protection is working , and we need to update the forms to add a CSFR token to the POST data.

Used CSRF Tokens using form helper or Manually

We have two way to add CSRF tokens; if we are thinking to update your form with CodeIgniter form helper class then CSRF tokens will automatic added or if you are thinking to adjust in custom form then we need to add custom hidden input name and its value.

When we will use form helper class:

<?php echo form_open(base_url( 'user/login' ), array( 'id' => 'login', 'class' => 'login' ));?>
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" value="Submit" />
<?php echo form_close();?>

Using form helper class will automatically added input filed into the form with a random token value to prevent CSRF.

Output:

<form action="http://localhost/codeigniter/index.php" method="post" accept-charset="utf-8"><div style="display:none">
<input type="hidden" name="csrf_test_name" value="0729bc908947526aa2e7951fb9066701" />
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" value="Submit" />

When we use custom form:

We need to add a input filed to prevent our custom form with CSRF.

For example:

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">

How to use in AJAX/jQuery Call

If we are using AJAX in our web application and token is not pass with POST data then CodeIgniter will return a error 500 (Internal Server Error). It mean we need to used CSRF token all the forms and pass with the POST data. There are many way to pass CSRF token with POST data and its depends on you because there are forms helper class which is automatically added and custom field where we need to manually coded and call CSRF token name and its random value.

For Example:

<!-- Add CSRF Token as Variable into HEAD -->
<script type="text/javascript">
   var csrf_token = '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<!-- Call AJAX code and used CSRF Token -->
<script type="text/javascript">
$.post('POST URL', { data: 'value', 'csrf_test_name': csrf_value }, function( response ) {
   // response
}, 'json' );
</script>

How to use CSRF in AJAX/jQuery Serialization

If you are think to used AJAX Serialization then you have very easy and just open and closed your form using form helper class of CodeIgniter.

For example:

<!-- create form with open_form() -->
<?php echo form_open(base_url( 'user/login' ), array( 'id' => 'login', 'class' => 'login' ));?>
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" value="Submit" />
<?php echo form_close();?>
<!-- Update AJAX code to post serialized data -->
<script type="text/javascript">
$.post( ajax_url, $('#login).serialize(), function( response ) {
// response
}, 'json' );
</script>

Disable CSRF for Third Party API

When we are using Third Party API or Facebook API / Twitter API in our website application then we need to disable CSRF protection in the response controller or function (method). For this we need to disable our controller or function only,

For example:

if (isset($_SERVER["REQUEST_URI"])) {
if (stripos($_SERVER["REQUEST_URI"], '/ajax/') === FALSE AND # all ajax controllers
stripos($_SERVER["REQUEST_URI"], '/facebook_app/) === FALSE AND # all facebook controllers
stripos($_SERVER["REQUEST_URI"], '/twitter_app/login') === FALSE AND # only login function
) {
$config['csrf_protection'] = TRUE;
} else {
$config['csrf_protection'] = FALSE;
}
} else {
$config['csrf_protection'] = TRUE;
}

7 Comments

  1. Federico August 17, 2015 1:07 pm Reply

    Great tutorial! Exactly what I was looking for. Does the info could be applied to CI 3?
    Thanks

    • admin August 18, 2015 8:23 am Reply

      Yes you can apply Codeigniter 3. For more details you can follow “Security Class” document of CI.

  2. ayub@dev March 21, 2016 7:46 pm Reply

    Thank you so much for this tutorial <3

  3. Aitazaz March 30, 2016 6:48 pm Reply

    Nice Tutorial !!! Do it prevent form from double submission. For example user has pressed the submit button and during the server side processing user get latency problem and user reload the page so it will be prevented or will be submitted again .. Actually i am looking for a method to avoid duplication using codeigniter builtin functionality unless using jquery and javascript to disable submit button .. duplication can also be occur if user press submit button twice . So my quest will CSRF prevent the double submission or not ??

    • admin April 7, 2016 3:45 pm Reply

      No it is not prevent double submission.

  4. Steve June 15, 2016 10:19 am Reply

    Hi,

    in codeigniter 3 isn’t neccessary to add a hidden input with CSRF if you use the Ci form_open(). That creaetes automatically.
    And your configuration solution won’t work form me on Facebook. The ‘An Error Was Encountered’ message still lives.

    Can you help me?

    Thanks!

    Steve

  5. Hamid Ali December 22, 2016 6:02 am Reply

    Perfect Tutorial Keep It Up
    Thanks

Post a Comment

Your email address will not be published. Required fields are marked *

*


  • Recent Posts

    • Secure Your CodeIgniter Application using CSRF Token

      27.10.2014
      by admin
      In this tutorial, we will learn how to make our website more secure & protect from CSRF when we are using CodeIgniter web application framework. We thanks CodeIgniter team who giving in built support Cross Site Rquest Forgery (CSRF or XSRF). To enable CSRF protection CodeIgniter Framework will automatically protect forms or AJAX calls from CSRF when […]
    • Multiple Themes in CodeIgniter like WordPress

      07.08.2014
      by admin
      Create multiple themes and select one of them from backend like wordpress is drawbacks of a framework. Similar CodeIgniter have not an option to select one theme from multiple theme concept but we can re arrange using CodeIgniter template concept. We are going to handle multiple themes in a very simple way, in this example […]
    • How to create REST API in PHP?

      13.07.2014
      by admin
      REST (Representational State Transfer) is the standard design architecture for developing web services API. It is simple easy to understand and developing client-server relationship API. REST takes advantage of the HTTP request methods to layer itself into the existing HTTP architecture. We can handle GET, PUT, POST, DELETE operations through it. A REST API allows […]
    • Basic security vulnerabilities in php code

      16.10.2013
      by admin
      Today I have informed PHP programmers of common security mistakes that can be overlooked in PHP scripts. In the beginning programmers fail to understand about the PHP security issues or how to make secure script. The wise programmer knows that the real question is how secure a site is. Here I have focus how to […]
    • Generating CAPTCHA Image Using PHP

      29.12.2009
      by admin
      The CAPTCHA is a very very useful test to prevent abuse on the websites. When you create a web form like registration, login, contact us, blog comment etc…, We are suffering day by day with unwanted email or web spam abuse. So if you use CAPTCHA on your website forms, this can help in stopping […]
Copyright © 2012-2013 Sujit Shah. .
Tags: PHP Programmer Nepal, Web Developer Nepal, Website Designer, CodeIgniter Developer, Yii Framework, Wordpres, OpenCart, Drupal, Front End Developer, Responsive Developer, Bootstrap, Foundation, Freelance PHP MySql Programmer Nepal, Expert Programmer Nepal, PHP, MySql, LAMP, Linux, Apache, SVN, JavaScript, Ajax, jQuery, HTML, HTML5, CSS, CSS3, XML, SOAP, PSD to XHTML, Responsive Web Design, Web Development, CMS, E-commerce, Classified, Job portal, Travel & tours, Penny Auction, Lowest Unique Bid Auction, Reverse Auction, Price Reveal Auction, Payment Gateway Integration, Nepal, India, Hong Kong, Australia, UK, USA, Singapore, Germany, Canada, Netherlands, New Zealand, Norway, Italy