CodeIgniter 4 CSRF Token with Ajax Request

Share this Article

When we develop any application, security should be taken care of it. We already have an article where you will find the complete basics of using CSRF token in CodeIgniter 4.

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.

Inside this article we will see CodeIgniter 4 CSRF Token with Ajax Request. Cross-Site Request Forgery (CSRF).

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.


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.


Settings Environment Variables

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.


Enable CodeIgniter 4 CSRF Feature

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.

Inside this we will see by App.php & Filters.php. For more information we can learn from here.

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

Search for all these variables into 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.

//.. Other routes

$routes->get("my-form", "Site::myForm");
$routes->post("submit-data", "Site::submitData");

Controller is the functional file. Firstly let’s load a helper at Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error.

$ php spark make:controller Site

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

Source code of /app/Controllers/Site.php

<?php

namespace App\Controllers;

class Site extends BaseController
{
    public function myForm()
    {
        return view("my-form");
    }

    public function submitData()
    {
        $data = $this->request->getVar(); // all form data into $data variable
        echo json_encode( array( 
           "status" => 1, 
           "message" => "Ajax processed", 
           "data" => $data 
        ));
    }
}

View File setup –

Create /app/Views/my-form.php

<!doctype html>
  
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Codeigniter 4 CSRF Token with Ajax Request Tutorial - Online Web Tutor</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  
  <script>
    var csrfName = '<?= csrf_token() ?>';
    var csrfHash = '<?= csrf_hash() ?>';  
  </script>
  
</head>

<body>
  <div class="container">

    <h2>CodeIgniter 4 CSRF Token with Ajax Request</h2>

    <form method="post" action="javascript:void(0)" id="frm-my-form">
      <p>
        Name: <input type="text" name="name" id="name" placeholder="Enter name"/>
      </p>
      <p>
        Email: <input type="email" name="email" id="email" placeholder="Enter email"/>
      </p>
      <p>
        Mobile: <input type="text" name="mobile" id="mobile" placeholder="Enter mobile"/>
      </p>
      <p>
        <button type="submit">Submit</button>
      </p>
    </form>
          
  </div>
  
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>  
          
  <script>
      $("#frm-my-form").on("submit", function(){
          var dataJson = { 
            [csrfName]: csrfHash, // adding csrf here
            name: $("#name").val(), 
            email: $("#email").val(),
            mobile: $("#mobile").val() 
          };

        $.ajax({
            url : "<?php echo base_url('submit-data'); ?>",
            type: 'post',
            data: dataJson, 
            dataType: "json",         
            success : function(data)
            {   
                console.log(data);
            }  
        });
      });    
  </script>        
          
</body>
          
</html>

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.


Application Testing

Start development server:

$ php spark serve

Application URL: http://localhost:8080/my-form

To learn about Session Fixation in CodeIgniter 4, Click here.

We hope this article helped you to learn about CodeIgniter 4 CSRF Token with Ajax Request 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