CakePHP 4 How To Add CSRF Token To Ajax Request

Reading Time: 4 minutes
4,391 Views

Inside this article we will see CakePHP 4 how to add CSRF token to Ajax Request. Article contains classified information about working with CSRF token value in CakePHP 4.

A CSRF (Cross-Site Request Forgery attack) token is a secure random token (e.g., synchronizer token or challenge token) that is used to prevent CSRF attacks. The token needs to be unique per user session and should be of large random value to make it difficult to guess.

In CakePHP 4, we can enable or disable this CSRF feature.

Learn More –

Let’s get started.


CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.


Generate & Use CSRF Token To Ajax

Here, we will see the steps to generate CSRF token and use in simple way to all ajax requests of application.

Steps #1

Generate CSRF Token (Meta Tag). We will use HTML helper of CakePHP and a method from it.

<?php

        echo $this->Html->meta("myToken", $this->request->getAttribute("csrfToken"));
        
?>

You can add this code to your head tag of parent layout or inside any of your template file.

This will generate this given output:

<meta name="myToken" content="G0WNm+/O4nIyO6k+P/Vm9Qw6kFanTuUAwLE3B+g73skKCKa4dD/gZBruENI/aSwdz7SO2dO1Va7KY8MnGX5plHzBPqgerE8+PguibsYrhzHz0lZi3Q+9+mgxnttEC9QAfIgn5wcPH3/40Ljs49FnyA=="/>

We can see meta tag with name and content attribute.

Step #2

We will read above token value from Meta tag and store this into a variable of javascript for use.

<script>

       var token = $("meta[name='myToken']").attr("content");

</script>

Step #3

Use above token to attach into request header. If you have a single ajax request then you send this token value with data property as a value. Otherwise in case have multiple ajax requests then we will do a global setup to add CSRF token value to request header.

$(document).ready(function() {

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': token
        }
    });

    // ... Your Ajax Requests
});

You don’t need to do anything within your ajax properties.

Now,

Whenever you fire an ajax request from application, you will find this add header token into request header.

We hope this article helped you to learn about CakePHP 4 How To Add CSRF Token To Ajax Request Tutorial 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