Cakephp 4 Authorization – Tutorial

Cakephp 4 authorization

Cakephp 4 Authorization, how to create a secure application protecting zones with the use of access policies

Cakephp 4 Authorization

First we will install the corresponding package with composer

composer require "cakephp/authorization:^2.0"

Then we proceed to add the corresponding code, we import each of the classes

use Authorization\AuthorizationService;
use Authorization\AuthorizationServiceInterface;
use Authorization\AuthorizationServiceProviderInterface;
use Authorization\Middleware\AuthorizationMiddleware;
use Authorization\Policy\OrmResolver;
use Psr\Http\Message\ResponseInterface;

We add the corresponding interfaces usually combined with the authentication class

class Application extends BaseApplication implements AuthorizationServiceProviderInterface

We add the corresponding plugin in the bootstrap() method


We proceed to incorporate the middleware

->add(new AuthorizationMiddleware($this))

We continue with the method and solve them

public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface
        $resolver = new OrmResolver();

        return new AuthorizationService($resolver);

It’s time to start loading the component in the AppController.php file


It’s time to use the class, we can add the following method in the controller that we want to bypass an authorization