Search code examples
cakephpcakephp-2.0csrfcakephp-2.1cakephp-2.2

Avoid CSRF attacks by creating form with JavaScript on CakePHP


CakePHP documentation says to avoid CSRF attacks it is necessary to include the Security component in the controller, and in addition, create the form using the FormHelper.

In my case, i need to create some form fields (such as a textarea) using JavaScript (jQuery) and therefor I can not use the FormHelper for them.

$('#body').html('<textarea name="data[post][body]" type="textarea" cols="30" rows="3">'+text+'</textarea>');

And of course, it doesn't pass the security and the form fails to be submitted.

Is there anyway I can create a secure Form creating some fields with JavaScript?

Thanks.


Solution

  • Well, one option you have is to unlock these fields so they are ignored in the security check. In your view, write:

    <?php $this->Form->unlockField('fieldname'); ?>
    

    Another option would be to create the form fields you want to add dynamically with the Form helper in a hidden area of the form and only show them if needed.