Quick Start
Installation
Install the plugin with Composer from your CakePHP project root, where composer.json is located:
php composer.phar require "cakephp/authorization:^3.0"Authorization 3.x is compatible with CakePHP 5.
Load the plugin in src/Application.php:
$this->addPlugin('Authorization');Getting Started
The Authorization plugin integrates into your application as middleware and, optionally, as a component that makes authorization checks easier in controllers.
In src/Application.php, add the required imports:
use Authorization\AuthorizationService;
use Authorization\AuthorizationServiceInterface;
use Authorization\AuthorizationServiceProviderInterface;
use Authorization\Middleware\AuthorizationMiddleware;
use Authorization\Policy\OrmResolver;
use Psr\Http\Message\ServerRequestInterface;2
3
4
5
6
Implement AuthorizationServiceProviderInterface on your application class:
class Application extends BaseApplication implements AuthorizationServiceProviderInterfaceThen register the middleware:
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
$middlewareQueue->add(new ErrorHandlerMiddleware(Configure::read('Error')))
->add(new AssetMiddleware())
->add(new RoutingMiddleware($this))
->add(new BodyParserMiddleware())
// If you use Authentication it must come before Authorization.
->add(new AuthenticationMiddleware($this))
// Add Authorization after routing, body parsing, and authentication.
->add(new AuthorizationMiddleware($this));
return $middlewareQueue;
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
AuthorizationMiddleware must be added after authentication so the request contains an identity for authorization checks.
The middleware calls a hook on your application to obtain the authorization service. Add this method to src/Application.php:
public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface
{
$resolver = new OrmResolver();
return new AuthorizationService($resolver);
}2
3
4
5
6
This configures the basic policy resolvers that map ORM entities to policy classes.
Next, load the component in src/Controller/AppController.php:
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Authorization.Authorization');
}2
3
4
5
With the AuthorizationComponent loaded, you can authorize resources per action:
public function edit($id = null)
{
$article = $this->Articles->get($id);
$this->Authorization->authorize($article, 'update');
// Rest of action
}2
3
4
5
6
7
Calling authorize() lets your policies enforce access-control rules. You can also check permissions anywhere you have access to the request identity.