CakePHP Security

Security is an essential feature for creating any web application. It provides surety to the website user that their data will be secure from unauthorized access. So, CakePHP uses some tools for security purposes in web applications.

The Security can be handled in the cakephp allocation by three ways –

  1. Security Utility
  2. CSRF
  3. Security Component

We will use this package to provide security in the CakePHP application. 

use Cake\Utility\Security;

Now we will learn about encryption and decryption of the text in the CakePHP application.

Encryption and Decryption

CakePHP provides some security library by which we can encrypt and decrypt text easily. These are the two methods used for security in your application.

 static Cake\Utility\Security::encrypt ($text, $key, $hmacSalt = null )
 static Cake\Utility\Security::decrypt ($cipher, $key, $hmacSalt = null ) 

In this method, we will pass two-argument text and key for encrypting the data, and it will return a value in encrypted form by use of HMAC checksum.

Similarly, we can also pass a two-argument ciphertext and key, where the key value will be the same as we use in encryption text, and the ciphertext value will be used in decrypting the text. Hence, the output of the encryption method will use as input for decoding the data. 

A hash() method is used for hashing the data like password which can change the format of text. Here is the syntax 

static Cake\Utility\Security::hash($string, $type = NULL, $salt = false)

Now we will create a program to show our data secure by the use of encryption and decryption methods.

Create a file LoginsController.php at src/Controller/LoginsController.php. Now write the following code in the LoginsController file.

 request->is( 'post' )) {
   $mname = $this->request->getData( 'username' );
   $nemail = $this->request->getData( 'password' );
   //use of encryption method
   $key = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
   $output1 = Security::encrypt( $mname, $key );
   $output2 = Security::encrypt( $nemail, $key );
   $this->set( 'result1', $output1 );
   $this->set( 'result2', $output2 );
 // use of decryption method
   $name1 = Security::decrypt( $output1, $key );
   $this->set('name1', $name1 );
   $name2 = Security::decrypt( $output2, $key );
   $this->set('name2', $name2 );
  }
  }
  }
 ?> 

Create a folder Logins at src/Template inside that folder create an index.ctp file. Now write the following code in index.ctp file.

 Form->create("Logins", array( 'url' =>'/Logins' ));
 echo $this->Form->input ('username', [ 'class'=>'fare-control', 'required', 'value' => '' ]);
 echo $this->Form->input( 'password', [ 'class'=>'fare-control', 'required' ,'value'=> '' ]);
 echo $this->Form->button('Submit');
 echo $this->Form->end();
  ?>
  
  "; ?>
  
  "; ?>
 
 "; ?>
 
 "; ?>
 
 "; ?>
  

Now execute the above code by writing the following URL

http://localhost/CakePHP/logins

When you run this code on localhost, you will show this output

CakePHP Security

After submitting the form, you will get your username and password in encryption as well as decryption form like this.

CakePHP Security 1

CSRF

A CSRF stands for Cross-Site Request Forgery. By loading the csrf in your application, you get protection against attacks. CSRF is a common vulnerable tool that allows an attacker to capture and re-send the previous request in web application. And sometimes, it sends a request using image tags or resources on other domains. The CSRF can enable by the use of CsrfComponent to your controller, as shown below.

 public function initialize() {
  parent::initialize();
  $this-> loadComponent('Csrf');
 }  

The CsrfComponent combines with Formhelper, and every time it creates a form with the use of FormHelper in CakePHP. It contains three configuration function which prevents your data from the unauthorized access in the web application.

  1. cookieName – It includes the name of the cookie which you want to pass in the csrf function. By default, it takes csrfToken.
  2. Expiry – It defines how long time the csrf token will be available in your application. By defaults, it makes the session time to expire the csrf token.
  3. Secure – It determines whether your cookie has been set with the secure flag or not. In csrf function, the cookie will set on the HTTPs connection, and if you tried to set your cookie in normal HTTP, then it will fail to set the cookie.
  4. Fields – You can prevent your form of data by defining the csrf function in the form fields. The default setting in form is _csrfToken.

When you enable the csrf token, you can handle the request-based object in your application.

$id = $this -> request ->getParam(‘_csrfToken’); 

       You can also disable the csrf component for certain actions in the controller by defining the controller’s event dispatcher beforeFilter () method:

 public function beforeFilter ( Event $event )
 { 
$this- >getEventManager () ->off ($this->Csrf);
 } 

Security

The CakePHP security component is used to provides tight security in the web application. There are some ways to provide security –

To HTTP, which restrict accepts your application – You should always check the http url in the browser before performing any action on the site. You can also check the HTTP method by use Cake\Network\Request:: allowMethod() for determining the correct HTTP in the web application.

Form tampering Protection – The CakePHP provides the security components to save the form from unauthorized users. The Security component prevents the form from these things –

  1. You can’t add the unnecessary fields in the form.
  2. Fields can’t be left blank.
  3. You can’t change the field’s name in the form.
  4. The users can’t update the hidden values.
  5. Use of SSL – All action should take place with SSL.
  6. Limiting cross controller communication – You can set the restriction in the controller to send request from another controller. Furthermore, you can also restrict the action in the controller’s action.

Here we have created an example of a security component.

Create a file SecuresController.php at src/Controller/SecuresController.php. Now write the given code in the SecuresController.php file.

 loadComponent('Security');
  }
  public function index()
  {
  $row = $this->Secures->newEntity();
  if ($this->request->is('post')) {
  $row = $this->Secures->patchEntity ($row, $this->request->getData());
  if ($this->Secures->save($row)) {
  $this->Security->requireSecure ();
  $this->Flash->success (__('successfully login'));
  return $this->redirect (['action' => 'index']);
  }
  $this->Flash->error (__('Technical issues'));
  }
  $this->set('row', $row);
  }
  }
 ?> 

Create a folder Secures at src/Template inside that folder create an index.ctp file. Now write the given code in index.ctp file.

 

Login Details

Form->create("Secures",array('url'=>'/secures')); echo $this->Form->input ('name'); echo $this->Form->input ('email'); echo $this->Form->input ('password'); echo $this->Form->button ('Submit'); echo $this->Form->end(); ?>

Now execute the above code by writing the following URL

http://localhost/CakePHP/Secures

Then it will show this Output.

CakePHP Security 2