Quick Start

Installation

Install the plugin with composer from your CakePHPProject’s ROOT directory (where the composer.json file is located)

  1. php composer.phar require cakephp/authorization

Load the plugin by adding the following statement in your project’ssrc/Application.php:

  1. $this->addPlugin('Authorization');
  2. // Prior to 3.6.0
  3. Plugin::load('Authorization');

Getting Started

The Authorization plugin integrates into your application as a middleware layerand optionally a component to make checking authorization easier. First, letsapply the middleware. In src/Application.php add the following to the classimports:

  1. use Authorization\AuthorizationService;
  2. use Authorization\AuthorizationServiceProviderInterface;
  3. use Authorization\Middleware\AuthorizationMiddleware;
  4. use Authorization\Policy\OrmResolver;
  5. use Psr\Http\Message\ResponseInterface;
  6. use Psr\Http\Message\ServerRequestInterface;

Add the AuthorizationProviderInterface to the implemented interfaces on your application:

  1. class Application extends BaseApplication implements AuthorizationServiceProviderInterface

Then add the following to your middleware() method:

  1. // Add authorization (after authentication if you are using that plugin too).
  2. $middleware->add(new AuthorizationMiddleware($this));

The AuthorizationMiddleware will call a hook method on your application whenit starts handling the request. This hook method allows your application todefine the AuthorizationService it wants to use. Add the following method yoursrc/Application.php:

  1. public function getAuthorizationService(ServerRequestInterface $request, ResponseInterface $response)
  2. {
  3. $resolver = new OrmResolver();
  4.  
  5. return new AuthorizationService($resolver);
  6. }

This configures a very basic Policy Resolvers that will matchORM entities with their policy classes.

Next lets add the AuthorizationComponent to AppController. Insrc/Controller/AppController.php add the following to the initialize()method:

  1. $this->loadComponent('Authorization.Authorization');

By loading the authorization component we’ll be able to checkauthorization on a per-action basis more easily. For example, we can do:

  1. public function edit($id = null)
  2. {
  3. $article = $this->Article->get($id);
  4. $this->Authorization->authorize('update', $article);
  5.  
  6. // Rest of action
  7. }

By calling authorize we can use our Policies to enforce ourapplication’s access control rules. You can check permissions anywhere by usingthe identity stored in the request.

Further Reading