CakePHP Security Component

Author - Manju Kashyap

CakePHP Security Component is very useful and provides an easy way to enable very tight security in our application:

1. It can restrict which HTTP methods our application accepts.
2. It provides Form Tampering Protection.
3. It can force to require that SSL must be used.
4. It can limit cross controller communication.

Cross-Site Request Forgery Protection:

Cross-Site Request Forgery is very common vulnerability in web applications. It can allow an attacker to capture and replay a request submitted by an authenticated user. This attack can be used to transfer funds, change a password and can be more destructive than that.

But, by using the Security Component we can automatically get CSRF and form tampering protection. Hidden token fields are automatically inserted into our forms and checked by the Security component when the request is submitted to the controller.

Note: When using the Security Component, we must use the FormHelper to create our forms.

Here is an example to explain its usage:

Add the security component in AppController as follows:

public $components = array(‘'Security' => array());

By default, CSRF tokens are valid for 30 minutes and expire on use but we can control how long tokens last by setting csrfExpires on the component as follows:

public $components = array(
'Security' => array(
'csrfExpires' => '+1 hour')

In beforeFilter function, following code is used to check for the urls which require an SSL connection (we blacklisted SSL security for the local site):

$url = env('HTTP_HOST');
if (!isset($_SERVER['HTTPS']) && strpos($url, 'local') === false) {

Then to handle any blackhole (unsecured request) and to take appropriate action we can use following callback method:

$this->Security->blackHoleCallback = ‘blackHole';

Following is the function to handle any black hole:

function blackHole($type) {
switch ($type) {
   case "csrf":
       // No cross form tampering, set flash, reload current window
       $this - > Session - > setFlash(__('The request has been black-holed (csrf)'));
       $this - > redirect(array('controller' => ABC, 'action' => xyz));
   case "auth":
       // Indicates a form validation error, or a controller/action mismatch error.
       $this - > Session - > setFlash(__('The request has been black-holed (auth)'));
       $this - > redirect(array('controller' => ABC, 'action' => xyz));
   case "secure":
       // Force SSL certificate
       $this - > redirect('https://'.env('SERVER_NAME').$this - > here);
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published.