CakePHP 4 How To Add CSRF Token To Ajax Request

Share this Article
Reading Time: 4 minutes
3,053 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.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5