Implementation of CodeIgniter 4 CSRF Token

Share this Article
Reading Time: 12 minutes
1,268 Views

When we create an application, we need to work simultaneously with the security parameter as well. Security parameters we always need to carry with the application development because we need to assure clients or the application owner that can work safely.

In every programming language which we use in daily life to create any type of application, they all have their security libraries and their in-built packages.

Here, inside this article we are covering in CodeIgniter 4. We will see complete guide to use CodeIgniter 4 CSRF Token. Cross-Site Request Forgery (CSRF).

Additionally we will see all other settings generally we do for CSRF token with forms in CodeIgniter 4.

To Learn about CodeIgniter 4 CSRF functions, Click here.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started about step by step Implementation of CSRF in CodeIgniter 4 Application.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Security Class in CodeIgniter 4 | In-Built Library

In CodeIgniter 4, we have a security class library. By the help of this library we can add and work with different different level of security patches in CodeIgniter 4 application.

Inside this very interesting article we are going to work with CodeIgniter 4 CSRF Token.

What is a Security class in CodeIgniter 4 ?

The Security Class of CodeIgniter 4 contains some methods that help to protect site and it’s functions against Cross-Site Request Forgery (CSRF) attacks.

In CodeIgniter 4, to load this library we use –

$security = \Config\Services::security();

What is Cross-site request forgery (CSRF) ?

Cross-Site Request Forgery (CSRF) is an attack which forces an end user (an unauthenticated user of site) to execute/run unwanted actions on a web application. These requests sometimes crash the database. This saves attacking data into database tables and execute accordingly and may down the application.

This is a normal attack which every development or even web owner needs to do it first.

How can we avoid CSRF attack in Web application ?

There are several ways to do it. Following are the easy way to follow and implement –

  • Enable CSRF token feature in web application.
  • Send CSRF token in every request of application.
  • Security library auto validates CSRF token from requests which requested to server.
  • Proceed with the application functions, if everything is fine.

Let’s see the guide to avoid CSRF attack in CodeIgniter 4.


Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Working with CodeIgniter 4 CSRF Token

To enable the features to avoid CSRF in CodeIgniter 4, we have to 2 options. Either we can do via .env file and/or by /app/Config/Filters.php including /app/Config/App.php.

We will see each step to enable and to work.

Open up .env file which is at project root.

You will see this piece of code into file.

# app.CSRFProtection = false
# app.CSRFTokenName = 'csrf_test_name'
# app.CSRFCookieName = 'csrf_cookie_name'
# app.CSRFExpire = 7200
# app.CSRFRegenerate = true
# app.CSRFExcludeURIs = []
# app.CSRFSameSite = 'Lax'

Find this line –

#app.CSRFProtection = false

Change it to (To enable CSRF),

app.CSRFProtection = true

Also other settings like name, expire time etc we can manage from .env file. Remove (#) comment all to use all settings.

app.CSRFTokenName = 'app_csrf'
app.CSRFCookieName = 'app_csrf_cookie'
app.CSRFExpire = 7200
app.CSRFRegenerate = true
app.CSRFExcludeURIs = []
app.CSRFSameSite = 'Lax'

app.CSRFExpire = 7200 Here, 7200 is in seconds. This is csrf expire time. If we don’t change it, then after 120 mins csrf token will be automatically regenerated if and only if app.CSRFRegenerate = true

Alternate CSRF Settings

Open /app/Config/App.php (For Configuration Settings) file –

Initial Code

public $CSRFTokenName = 'csrf_test_name';
public $CSRFHeaderName = 'X-CSRF-TOKEN';
public $CSRFCookieName = 'csrf_cookie_name';
public $CSRFExpire = 7200;
public $CSRFRegenerate = true;
public $CSRFRedirect = true;

Now, if we want to update token name, CSRF cookie name, CSRF time for regenerate, then accordingly we can do all these settings.

public $CSRFTokenName = 'app_csrf';
public $CSRFHeaderName = 'X-CSRF-TOKEN';
public $CSRFCookieName = 'app_csrf_cookie';
public $CSRFExpire = 7200;
public $CSRFRegenerate = true;
public $CSRFRedirect = true;

Open up the file /app/Config/Filters.php (To Enable CSRF & Route Control)

Update $globals settings into this file. Remove comment from csrf.

//...

public $globals = [
  'before' => [
    //'honeypot'
     'csrf',
  ],
  'after'  => [
    'toolbar',
    //'honeypot'
  ],
];

Successfully, we have enabled all settings for CSRF and now ready to work with it.


Application Settings – Routes, Controller & View

We are going to use and see how we can implment CodeIgniter 4 CSRF token into application form.

Let’s configure /app/Config/Routes.php first.

//...

$routes->match(["get", "post"], "/first-form", "Site::firstForm");
$routes->match(["get", "post"], "/second-form", "Site::secondForm");

Creating Site controller now. Controllers will be created inside /app/Controllers directory.

$ php spark make:controller Site

Source code of /app/Controllers/Site.php

<?php

namespace App\Controllers;

class Site extends BaseController
{
    public function firstForm()
    {
        if ($this->request->getMethod() == "post") {

            // handle post request here
        }
        return view("first-form");
    }

    public function secondForm()
    {
        if ($this->request->getMethod() == "post") {

            // handle post request here
        }
        return view("second-form");
    }
}

View File setup –

Create /app/Views/first-form.php

<form method="post" action="<?php echo site_url('first-form') ?>">
  
  <input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />
  
  <p>
    Name: <input type="text" name="name" placeholder="Enter name"/>
  </p>
  <p>
    Email: <input type="email" name="email" placeholder="Enter email"/>
  </p>
  <p>
    Mobile: <input type="text" name="mobile" placeholder="Enter mobile"/>
  </p>
  <p>
    <button type="submit">Submit</button>
  </p>
</form>

When we enable CSRF into CodeIgniter 4 application, automatically csrf_token() & csrf_hash() these 2 functions will be available to use. If you are getting any error while loading these functions it means your application is not configured in a right way.

When we run application to browser, you will see the added code of CSRF will generate the HTML values as

<input type="hidden" name="app_csrf" value="9b1328cbae24c87ffdfcfe9af248abc6">
  

Inside this first-form.php, as you can see we have used CSRF to generate a token and send it when we submit this form to server.

Also, if we don’t want to use csrf_token() & csrf_hash() functions to access CSRF settings, we can also do the same task with the help of a single function without even writing HTML hidden input code. So, either

<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />
  
  OR
  
<?= csrf_field() ?>
  

Processing first-form.php POST request with CSRF token –

public function firstForm()
{
  if ($this->request->getMethod() == "post") {

    print_r($this->request->getVar());
    // rest we can do all code here.
  }
  return view("first-form");
}

Keep in mind, when we have enabled the feature of CSRF token in CodeIgniter 4 application, it means we have to pass token in every request either it will be a Post request via form or via Ajax request.

But in case, if we want to exclude some routes from this. Means we don’t want to use CSRF token in some requests, So how can we control the work flow. Let’s see about this.


Exclude Routes with NO CSRF Token

As you can see we have configured 2 routes in Routes.php at above settings. Just say, we are not going to use CSRF token in second-form.php view layout.

Let’s create a form layout for this view file –

<form method="post" action="<?php echo site_url('second-form') ?>">
  
  <p>
    Name: <input type="text" name="name" placeholder="Enter name"/>
  </p>
  <p>
    Email: <input type="email" name="email" placeholder="Enter email"/>
  </p>
  <p>
    Mobile: <input type="text" name="mobile" placeholder="Enter mobile"/>
  </p>
  <p>
    <button type="submit">Submit</button>
  </p>
      
</form>
      

Inside this form, we are not using CSRF related functions to generate token. So when we submit this request to server, it will not process.

Next, what we have to – We need to exclude this Application route from CSRF list. We need to tell application that in this case you don’t need to look for CSRF token, only submit that.

Adding Routes to exclude list of CSRF

Back to /app/Config/Filters.php file

public $globals = [
  'before' => [
    //'honeypot'
    'csrf' =>['except' => ['/second-form']],
  ],
  'after'  => [
    'toolbar',
    //'honeypot'
  ],
];

When we do this setting then on posting data, request will not be validated by CSRF. For more routes into exclude list simply you need to add more routes as the array values.

[‘except’ => [‘/second-form’, ‘/other-route’, …]]

We hope this article helped you to learn about Implementation of CSRF token in CodeIgniter 4 in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment