The CsrfComponent was deprecated since CakePHP version 3.5.0. On CakePHP 4, we now have a new middleware to help us protect applications against Cross Site Request Forgery attacks. In this article, we are going to show the different ways to enable and disable Cross Site Request Forgery between the controller and the new middleware.
Do these changes:
In your Application::middleware add
$this->loadComponent('Csrf')from your controllers.
The configuration keys from CsrfComponent
field are also available in the middleware. If you used any of these, you should be able to continue using the middleware.
Is not recommended to disable CSRF, but sometimes you really need to. With the component you could have something like this in your controller:
Now with the middleware, we can use the method
skipCheckCallback to disable Csrf based on a custom logic:
That’s it, we have migrated CSRF protection from CsrfComponent to CsrfProtectionMiddleware.