### Install CakePHP Authorization Plugin Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/index.md Install the plugin using Composer. Ensure you are in your CakePHP project root. ```bash php composer.phar require "cakephp/authorization:^3.0" ``` -------------------------------- ### Create Request Policy Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/request-authorization-middleware.md Implement the `RequestPolicyInterface` to define authorization logic for requests. This example allows access to the 'ArticlesController::index' action. ```php namespace App\Policy; use Authorization\Policy\RequestPolicyInterface; use Authorization\Policy\ResultInterface; use Cake\Http\ServerRequest; class RequestPolicy implements RequestPolicyInterface { public function canAccess($identity, ServerRequest $request): bool|ResultInterface { if ($request->getParam('controller') === 'Articles' && $request->getParam('action') === 'index' ) { return true; } return false; } } ``` -------------------------------- ### Implement BeforeScopeInterface for Scope Pre-conditions - PHP Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policies.md Implement `BeforeScopeInterface` to add pre-condition checks for scope methods. This example prevents trial users from accessing paid-only articles by modifying the query. ```php namespace App\Policy; use Authorization\Policy\BeforeScopeInterface; class ArticlesTablePolicy implements BeforeScopeInterface { public function beforeScope($user, $query, $action) { if ($user->getOriginalData()->is_trial_user) { return $query->where(['Articles.is_paid_only' => false]); } return null; } } ``` -------------------------------- ### Get Authorization Service Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/index.md Implement the `getAuthorizationService` method in `src/Application.php` to configure the authorization service with a policy resolver. ```php public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface { $resolver = new OrmResolver(); return new AuthorizationService($resolver); } ``` -------------------------------- ### Implement BeforePolicyInterface for Global Checks - PHP Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policies.md Use the `BeforePolicyInterface` to define a `before()` method that runs common checks before other authorization methods in a policy. This example allows admin users to bypass other checks. ```php namespace App\Policy; use Authorization\IdentityInterface; use Authorization\Policy\BeforePolicyInterface; use Authorization\Policy\ResultInterface; class ArticlesPolicy implements BeforePolicyInterface { public function before(?IdentityInterface $identity, mixed $resource, string $action): ResultInterface|bool|null { if ($identity->getOriginalData()->is_admin) { return true; } return null; } } ``` -------------------------------- ### Install CakePHP Authorization Plugin with Composer Source: https://github.com/cakephp/authorization/blob/3.x/readme.md Use this command to add the authorization plugin to your CakePHP project via Composer. ```bash composer require cakephp/authorization ``` -------------------------------- ### Load Authorization Plugin in CakePHP Source: https://github.com/cakephp/authorization/blob/3.x/readme.md After installation, load the Authorization plugin into your CakePHP application using the cake console. ```bash bin/cake plugin load Authorization ``` -------------------------------- ### Combine MapResolver and OrmResolver with ResolverCollection Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policy-resolvers.md Use ResolverCollection to chain multiple resolvers, allowing for a prioritized lookup. This example checks explicit maps before falling back to convention-based ORM resolution. ```php use Authorization\Policy\ResolverCollection; use Authorization\Policy\MapResolver; use Authorization\Policy\OrmResolver; $ormResolver = new OrmResolver(); $mapResolver = new MapResolver(); $resolver = new ResolverCollection([$mapResolver, $ormResolver]); ``` -------------------------------- ### Check Authorization with Boolean Result Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/component.md Use `can()` to check authorization and get a boolean result instead of throwing an exception. Useful for conditional logic. ```php if ($this->Authorization->can($article, 'update')) { // Do something to the article } ``` -------------------------------- ### Load Authorization Plugin in Application Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/index.md Load the Authorization plugin in your `src/Application.php` file. ```php $this->addPlugin('Authorization'); ``` -------------------------------- ### Load Authorization Component in Controller Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/index.md Load the `AuthorizationComponent` in your `src/Controller/AppController.php` file's `initialize` method. ```php public function initialize(): void { parent::initialize(); $this->loadComponent('Authorization.Authorization'); } ``` -------------------------------- ### Implement AuthorizationServiceProviderInterface Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/index.md Implement `AuthorizationServiceProviderInterface` on your application class in `src/Application.php`. ```php class Application extends BaseApplication implements AuthorizationServiceProviderInterface ``` -------------------------------- ### Create Basic Entity Policy - PHP Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policies.md Define a basic policy class for an entity. Ensure it resides in the `src/Policy` directory and follows the `EntityNamePolicy` naming convention. No base class or interface is strictly required. ```php 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)); ``` -------------------------------- ### Map Resource to Factory Callable with MapResolver Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policy-resolvers.md Use a factory callable with MapResolver to dynamically create policy instances when needed. The callable receives the resource and resolver instance, and should return a policy object. ```php use Authorization\Policy\MapResolver; $mapResolver = new MapResolver(); // Map a resource class to a factory callable $mapResolver->map(Article::class, function ($resource, $mapResolver) { // Return a policy object. }); ``` -------------------------------- ### Map Resource to Policy Instance with MapResolver Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policy-resolvers.md Map a resource class to an already instantiated policy object using MapResolver. This can be useful for policies with specific initialization requirements. ```php use Authorization\Policy\MapResolver; $mapResolver = new MapResolver(); // Map a resource class to a policy instance $mapResolver->map(Article::class, new ArticlePolicy()); ``` -------------------------------- ### Import Authorization Classes Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/index.md Add the required imports for Authorization classes in `src/Application.php`. ```php use Authorization\AuthorizationService; use Authorization\AuthorizationServiceInterface; use Authorization\AuthorizationServiceProviderInterface; use Authorization\Middleware\AuthorizationMiddleware; use Authorization\Policy\OrmResolver; use Psr\Http\Message\ServerRequestInterface; ``` -------------------------------- ### Map Controller Actions to Policy Methods Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/component.md Use `mapActions()` or `mapAction()` to define custom mappings between controller action names and their corresponding policy method names. ```php $this->Authorization->mapActions([ 'index' => 'list', 'delete' => 'remove', 'add' => 'insert', ]); ``` ```php $this->Authorization ->mapAction('index', 'list') ->mapAction('delete', 'remove') ->mapAction('add', 'insert'); ``` ```php public function add() { $this->Authorization->authorizeModel(); } ``` -------------------------------- ### Add AuthorizationMiddleware to Application Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md Implement AuthorizationServiceProviderInterface and add AuthorizationMiddleware to the middleware queue. The getAuthorizationService method is required to configure the authorization service. ```php namespace App; use Authorization\AuthorizationService; use Authorization\AuthorizationServiceInterface; use Authorization\AuthorizationServiceProviderInterface; use Authorization\Middleware\AuthorizationMiddleware; use Authorization\Policy\OrmResolver; use Cake\Http\BaseApplication; use Psr\Http\Message\ServerRequestInterface; class Application extends BaseApplication implements AuthorizationServiceProviderInterface { public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface { $resolver = new OrmResolver(); return new AuthorizationService($resolver); } public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue { $middlewareQueue->add(new AuthorizationMiddleware($this)); return $middlewareQueue; } } ``` -------------------------------- ### Apply Policy Scopes to Queries Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/component.md Apply policy scopes to queries using `applyScope()` to filter results based on authorization policies. Raises `MissingIdentityException` if no user is logged in. ```php $query = $this->Authorization->applyScope($this->Articles->find()); ``` ```php public function index() { $query = $this->Articles->find(); $this->Authorization->applyScope($query); } ``` -------------------------------- ### Map Resource to Policy Classname with MapResolver Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policy-resolvers.md Use MapResolver to explicitly map a resource class to a policy classname. Ensure the policy class exists and follows naming conventions. ```php use Authorization\Policy\MapResolver; $mapResolver = new MapResolver(); // Map a resource class to a policy classname $mapResolver->map(Article::class, ArticlePolicy::class); ``` -------------------------------- ### Specify Exceptions for Redirect Handling Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md Define specific exception classes that should trigger the redirect handler. This allows for granular control over which authorization failures result in a redirect. ```php 'exceptions' => [ MissingIdentityException::class, ForbiddenException::class, ], ``` -------------------------------- ### Map Request Class to Policy Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/request-authorization-middleware.md Configure the `AuthorizationService` in `Application::getAuthorizationService()` to map the `ServerRequest` class to your custom `RequestPolicy`. ```php use App\Policy\RequestPolicy; use Authorization\AuthorizationService; use Authorization\AuthorizationServiceInterface; use Authorization\Middleware\AuthorizationMiddleware; use Authorization\Middleware\RequestAuthorizationMiddleware; use Authorization\Policy\MapResolver; use Cake\Http\ServerRequest; use Psr\Http\Message\ServerRequestInterface; public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface { $mapResolver = new MapResolver(); $mapResolver->map(ServerRequest::class, RequestPolicy::class); return new AuthorizationService($mapResolver); } ``` -------------------------------- ### Configure OrmResolver with Namespace and Overrides Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policy-resolvers.md Customize OrmResolver by providing the application namespace and an array of class name overrides. This helps OrmResolver correctly locate policies for namespaced or aliased resources. ```php use Authorization\Policy\OrmResolver; $appNamespace = 'App'; $overrides = [ 'Blog' => 'Cms', ]; $resolver = new OrmResolver($appNamespace, $overrides); ``` -------------------------------- ### Configure Redirect Handler for Unauthorized Requests Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md Configure the middleware to use the built-in 'Redirect' handler for unauthorized requests. Specify the redirect URL, query parameter for the original URL, and a list of exception classes that should trigger the redirect. You can also define allowed file extensions to prevent redirecting API requests. ```php use Authorization\Exception\MissingIdentityException; $middlewareQueue->add(new AuthorizationMiddleware($this, [ 'unauthorizedHandler' => [ 'className' => 'Authorization.Redirect', 'url' => '/pages/unauthorized', 'queryParam' => 'redirectUrl', 'exceptions' => [ MissingIdentityException::class, OtherException::class, ], 'allowedRedirectExtensions' => ['csv', 'pdf'], ], ])); ``` -------------------------------- ### Load Request Authorization Middleware Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/request-authorization-middleware.md Add `RequestAuthorizationMiddleware` to your application's middleware queue after `AuthorizationMiddleware`. ```php public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue { $middlewareQueue->add(new AuthorizationMiddleware($this)); $middlewareQueue->add(new RequestAuthorizationMiddleware()); return $middlewareQueue; } ``` -------------------------------- ### Implement canEdit Policy Method - PHP Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policies.md Write a policy method to check if a user can edit a specific article. This method compares the user's ID with the article's user ID. ```php public function canEdit(IdentityInterface $user, Article $article): bool { return $user->id === $article->user_id; } ``` -------------------------------- ### Authorize Controller Actions Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/component.md Manually authorize controller actions using `authorize()`. If the action name is omitted, the request action is used. Throws `ForbiddenException` on denial. ```php public function edit($id) { $article = $this->Articles->get($id); $this->Authorization->authorize($article); // Rest of edit method } ``` ```php $this->Authorization->authorize($article, 'update'); ``` ```php public function delete($id) { $article = $this->Articles->get($id); $this->Authorization->authorize($article); } ``` -------------------------------- ### ControllerResolver for Controller Resources Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policy-resolvers.md Create a custom resolver that identifies Controller instances and returns a ControllerHookPolicy. This allows the Authorization plugin to work with existing controller-based authorization logic. ```php // in src/Policy/ControllerResolver.php namespace App\Policy; use Authorization\Policy\Exception\MissingPolicyException; use Authorization\Policy\ResolverInterface; use Cake\Controller\Controller; class ControllerResolver implements ResolverInterface { public function getPolicy($resource) { if ($resource instanceof Controller) { return new ControllerHookPolicy(); } throw new MissingPolicyException([get_class($resource)]); } } ``` -------------------------------- ### Check Single Resource Authorization with `canResult()` Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/checking-authorization.md Use `canResult()` when your policies return result objects. Inspect the status of the result object to determine if the action is permitted. ```php $result = $user->canResult('delete', $article); if ($result->getStatus()) { // Do deletion } ``` -------------------------------- ### ControllerHookPolicy for Legacy Authorization Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policy-resolvers.md Implement a catch-all policy that delegates authorization decisions to legacy controller methods. This is useful during migration from AuthComponent. ```php // in src/Policy/ControllerHookPolicy.php namespace App\Policy; class ControllerHookPolicy { public function __call(string $name, array $arguments) { /** @var ?\Authorization\Identity $user */ [$user, $controller] = $arguments; return $controller->isAuthorized($user?->getOriginalData()); } } ``` -------------------------------- ### Configure Custom Unauthorized Handler Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md Configure the middleware to use a custom unauthorized handler class. Pass the custom handler's class name to 'className' and any additional parameters required by your handler. This allows for flexible and custom handling of unauthorized requests. ```php use Authorization\Exception\ForbiddenException; use Authorization\Exception\MissingIdentityException; $middlewareQueue->add(new AuthorizationMiddleware($this, [ 'unauthorizedHandler' => [ 'className' => 'CustomRedirect', 'url' => '/users/login', 'queryParam' => 'redirectUrl', 'exceptions' => [ MissingIdentityException::class, ForbiddenException::class, ], 'custom_param' => true, ], ])); ``` -------------------------------- ### Use User Class as Identity with Authorization Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md Implement Authorization\IdentityInterface in your User entity and configure the identityDecorator option in AuthorizationMiddleware to use your User class directly as the identity. ```php namespace App\Model\Entity; use Authorization\AuthorizationServiceInterface; use Authorization\IdentityInterface; use Authorization\Policy\ResultInterface; use Cake\ORM\Entity; class User extends Entity implements IdentityInterface { public function can(string $action, mixed $resource): bool { return $this->authorization->can($this, $action, $resource); } public function canResult(string $action, mixed $resource): ResultInterface { return $this->authorization->canResult($this, $action, $resource); } public function applyScope(string $action, mixed $resource, mixed ...$optionalArgs): mixed { return $this->authorization->applyScope($this, $action, $resource, ...$optionalArgs); } public function getOriginalData(): \ArrayAccess|array { return $this; } public function setAuthorization(AuthorizationServiceInterface $service): static { $this->authorization = $service; return $this; } } ``` ```php $middlewareQueue->add(new AuthorizationMiddleware($this, [ 'identityDecorator' => function ($auth, $user) { return $user->setAuthorization($auth); }, ])); ``` -------------------------------- ### Attach Middleware to Application Controller Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/request-authorization-middleware.md When fallback routing is enabled, attach `RequestAuthorizationMiddleware` to your application controller to handle asset 404s and missing controllers. Configuration options like `unauthorizedHandler` can be passed. ```php public function initialize(): void { parent::initialize(); $this->middleware(function ($request, $handler): ResponseInterface { $config = [ 'unauthorizedHandler' => [ // ... ], ]; $middleware = new RequestAuthorizationMiddleware($config); return $middleware->process($request, $handler); }); } ``` -------------------------------- ### Add Custom Flash Message on Redirect Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md Create a custom unauthorized handler by extending the built-in 'RedirectHandler'. Override the 'handle' method to add custom logic, such as displaying a flash message, before returning the response from the parent handler. This allows for custom side effects when a redirect occurs. ```php getFlash()->error('You are not authorized to access that location'); return $response; } } ``` -------------------------------- ### Configure Automatic Authorization Checks Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/component.md Configure the component to automatically authorize actions based on the controller's default model and current action. Use `authorizeModel()` for specific actions. ```php $this->Authorization->authorizeModel('index', 'add'); ``` -------------------------------- ### Generate Empty ORM Policy Classes - Bash Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policies.md Use the CakePHP Bake console to generate empty policy classes for entities or tables. This is a convenient way to scaffold policy files. ```bash # Create an entity policy bin/cake bake policy --type entity Article # Create a table policy bin/cake bake policy --type table Articles ``` -------------------------------- ### Check Single Resource Authorization with `can()` Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/checking-authorization.md Use `can()` to check if the authenticated user has permission to perform an action on a specific resource. This is typically used for ORM entities or domain objects. ```php $user = $this->request->getAttribute('identity'); if ($user->can('delete', $article)) { // Do delete operation } ``` -------------------------------- ### Return Policy Result Object - PHP Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policies.md Instead of a boolean, return a `Result` object from a policy method to provide additional context, such as a failure reason. This allows for more granular control and feedback. ```php use Authorization\Policy\Result; public function canUpdate(IdentityInterface $user, Article $article): Result { if ($user->id === $article->user_id) { return new Result(true); } return new Result(false, 'not-owner'); } ``` -------------------------------- ### Authorize Resource in Controller Action Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/index.md Use the `AuthorizationComponent` to authorize a resource within a controller action. This enforces access-control rules defined in your policies. ```php public function edit($id = null) { $article = $this->Articles->get($id); $this->Authorization->authorize($article, 'update'); // Rest of action } ``` -------------------------------- ### Skip Authorization for Specific Actions Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/component.md Mark controller actions as public by skipping authorization. This can be done during component loading or within an action. ```php $this->loadComponent('Authorization.Authorization', [ 'skipAuthorization' => [ 'login', ], ]); ``` ```php public function view($id) { $this->Authorization->skipAuthorization(); } ``` -------------------------------- ### Apply Scope Conditions to Collections Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/checking-authorization.md Use `applyScope()` to filter collections, such as paginated queries, ensuring only accessible records are returned. This is useful for applying authorization rules to lists of resources. ```php $user = $this->request->getAttribute('identity'); $query = $user->applyScope('index', $query); ``` -------------------------------- ### Retrieve Original Identity Data Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md When the request identity is decorated by Authorization Middleware, use getOriginalData() to access the underlying identity object. ```php $originalUser = $user->getOriginalData(); ``` -------------------------------- ### User Class Implementing Both Authentication and Authorization Interfaces Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md If using both CakePHP Authentication and Authorization plugins, ensure your User class implements both Authentication\IdentityInterface and Authorization\IdentityInterface. ```php use Authentication\IdentityInterface as AuthenticationIdentity; use Authorization\IdentityInterface as AuthorizationIdentity; class User extends Entity implements AuthorizationIdentity, AuthenticationIdentity { public function getIdentifier(): int|string|null { return $this->id; } } ``` -------------------------------- ### Define Index Scope for Table Policy - PHP Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/policies.md Create a scope method in a table policy to modify queries. The `scopeIndex` method shown here restricts query results to articles belonging to the current user. ```php namespace App\Policy; class ArticlesTablePolicy { public function scopeIndex($user, $query) { return $query->where(['Articles.user_id' => $user->getIdentifier()]); } } ``` -------------------------------- ### Disable Authorization Check Requirement Source: https://github.com/cakephp/authorization/blob/3.x/docs/en/middleware.md To disable the default behavior where AuthorizationMiddleware raises an exception if authorization checks are not performed or bypassed, set 'requireAuthorizationCheck' to false. ```php $middlewareQueue->add(new AuthorizationMiddleware($this, [ 'requireAuthorizationCheck' => false, ])); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.