How To work with CodeIgniter 4 CSRF Token Tutorial

Reading Time: 12 minutes
19,904 Views

Inside this article we will see the concept i.e How To work with CodeIgniter 4 CSRF Token. Article contains the classified information about CSRF basics & How to use token in application.

CSRF stands for Cross-Site Request Forgery.

PHP Concept: What is CSRF Token and How To Use in Core PHP Tutorial

Whenever we create any 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.

To Learn about CodeIgniter 4 CSRF functions, Click here.

Learn More –

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

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.

Environment (.env) Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# 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.

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 How To work with CodeIgniter 4 CSRF Token in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more