Sometimes, I need to disable the Security component for certain actions in the controller. For example, if I need to handle FineUpload.
If I do not disable the Security component, I get a “request has been blackholed” error.
<?php class NewsController extends AppController { public $helpers = array('Html', 'Form'); public $components = array('RequestHandler', 'Security'); public function beforeFilter() { parent::beforeFilter(); if (AuthComponent::user('role') === 'admin' OR AuthComponent::user('role') === 'user') { //only allow access to these actions when the role is admin/user $this->Auth->allow('index', 'add', 'edit', 'delete', 'view', 'fineupload'); //Here, we disable the Security component for Ajax requests and for the "fineupload" action if(isset($this->Security) && ($this->RequestHandler->isAjax() || $this->RequestHandler->isPost()) && $this->action == 'fineupload'){ $this->Security->validatePost = false; $this->Security->enabled = false; $this->Security->csrfCheck = false; } } } /*rest of the code*/ |
You can still make secure ajax calls using Cake’s provided form security mechanics, without having to set unlocked fields or actions.
To do this, render a non-visible form and place inputs to store the ajax call parameters. Then, with Javascript set these parameters in your form and do the ajax call by serializing it. Remember that if you have CSRF check enabled (and one-token-per-session is disabled) you will have to update the form with a new valid CSRF token (you can read it in the controller with `$this->request->params['_Token']['key']`).
Example:
Form->create('AjaxForm');
echo $this->Form->hidden('value');
echo $this->Form->end();
?>
function makeAjaxCall() {
$.post(
ajaxUrl,
$('#AjaxForm').serialize(),
function(data) {
$('#AjaxForm [name="data[_Token][key]"]').val(data.newCsrfToken)
}
);
};
For further reference, we have created a component that allows to maintain security enabled on client side forms that are dinamically modified, and removes the need to unlock fields or actions when making ajax calls. You can find it at https://github.com/QTSdev/DynamicSecurity.