0
votes

I have enabled csrf security component in CakePHP v3. in AppConroller.php file in initialize() method

public function initialize() {

    // some of my other initialization here
    $this->loadComponent('Csrf');

    // some of my other initialization here

}

in View side I am using below code

echo $this->Form->create(....);
// some of other stuffs
echo $this->Form->end();

Yes, it will display CSRF token in hidden field below of form tag with CSRF Token value. BUT, after Page Reload.. CSRF token value remain same.

Actual concept of CSRF token, on every request it will generate new CSRF token. so how can we achieve this in CakePHP v3?

2

2 Answers

0
votes

There is actually no need to create a new csrf token for every request in most applications. One per user session is fine, and also improves usability (users can use back button, etc.). If the token is generated upon logon, an attacker can still not guess it to create external requests to the application. Having said that, a new csrf token per request can be slightly more secure and probably less prone to implementation errors, but that's not the weakest point in most applications.

For a more detailed explanation, have a look here.

0
votes

CakePHP creates a csrf token when the form is created, only if there isn't one that is already set. You would need to write a script that deletes the cookie if it exists. By default the cookie name is csrfToken but can be set manually using cookieName as a param when you initialize $this->loadComponent('Csrf');

Something along the lines of:

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

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    $cookieData = $this->request->cookie('csrfToken');
    if ($cookieData) {
        $this->Cookie->delete('csrfToken');
    }
}

The csrfComponent is in vendor/cakephp/cakephp/src/controller/component/CsrfComponent.php