AJAX requests in CakePHP without disabling SecurityComponent

Security is always a big deal for a software specially for web app where you don’t know your users’ intention. To ensure some common security measure, CakePHP provides SecurityComponent with its core.

Let’s come to the point. If you try to POST any request through AJAX, you will get Bad Request exception and your request will be Black Holed.

So, how do you prevent this without disabling the SecurityComponent for the action(many online resources do this. But this is not what we want, right?)? Well, you need to do 2 things to do in your beforeFilter to achieve that.

$this->action == 'add') {
    $this->Security->csrfUseOnce = false; // We will use CSRF token for more than one time
    $this->Security->validatePost = false; // Disabling form POST validation
}

Why these two:

  1. Since we may do the request several time from different parts of a single page, we will use same CSRF token. Though there is a complex way to update CSRF token of the page after the ajax request processed, but lets stick with the easier way.
  2. Also, SecurityComponent require you create your form using FormHelper shipped with CakePHP core. I’m assuming the form is not built with the FormHelper. You can ignore this if you generate your form using FormHelper.

If you do not using FormHelper to ensure CSRF protection you will need to post CSRF token with your post data in specific format. Here is how the CSRF token should be in post data.

array( 
'_Token' => array(
    'key'=> $this->Session->read('_Token.key');
    ),
'ModelName' => array(
    // modeldata
    )
)
Like
Like Love Haha Wow Sad Angry

Leave a Reply

Your email address will not be published.