diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 72849592..fada0167 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -45,6 +45,12 @@ const config = { // Please change this to your repo. // Remove this to remove the "edit this page" links. editUrl: 'https://github.com/lm-commons/lmcrbacmvc/tree/master/docs/', + includeCurrentVersion: false, + versions: { + "3.4": { + banner: 'none', + } + } }, blog: { showReadingTime: true, diff --git a/docs/versioned_docs/version-4.0/Guides/debugging.md b/docs/versioned_docs/version-4.0/Guides/debugging.md new file mode 100644 index 00000000..95166a85 --- /dev/null +++ b/docs/versioned_docs/version-4.0/Guides/debugging.md @@ -0,0 +1,26 @@ +--- +sidebar_position: 4 +sidebar_label: Debugging Tools +--- + +# Debugging Tools + +[LmcRbacMvcDeveloperTools](https://github.com/LM-Commons/LmcRbacMvcDeveloperTools) is an extension +for the [Laminas Developer Tools](https://github.com/laminas/laminas-developer-tools), +that collects and displays debugging data on settings, guards and roles. + +## Installation + +```shell +$ composer require --dev lm-commons/lmc-rbac-mvc-devtools +``` + +Composer should ask to install the module. Typically, this module will go in `development.config.php`. + +## Toolbar + +LmcRbacMvcDeveloperTools provides toolbars to view settings, guards and roles: + +![Settings](images/settings.png) +![Guards](images/guards.png) +![Roles](images/roles.png) diff --git a/docs/docs/cookbook.md.bak b/docs/versioned_docs/version-4.0/Guides/example.md similarity index 88% rename from docs/docs/cookbook.md.bak rename to docs/versioned_docs/version-4.0/Guides/example.md index e5d5ecbb..a6ce3610 100644 --- a/docs/docs/cookbook.md.bak +++ b/docs/versioned_docs/version-4.0/Guides/example.md @@ -1,12 +1,7 @@ --- -sidebar_position: 8 +title: A Real World Example +sidebar_position: 1 --- -# Cookbook - -This section will help you further understand how LmcRbacMvc works by providing more concrete examples. If you have -any other recipe you'd like to add, please open an issue! - -## A Real World Application In this example we are going to create a very little real world application. We will create a controller `PostController` that interacts with a service called `PostService`. For the sake of simplicity we will only @@ -15,9 +10,9 @@ cover the `delete`-methods of both parts. Let's start by creating a controller that has the `PostService` as dependency: ```php -class PostController +class PostController extends \Laminas\Mvc\Controller\AbstractActionController { - protected $postService; + protected PostService $postService; public function __construct(PostService $postService) { @@ -28,7 +23,7 @@ class PostController public function deleteAction() { - $id = $this->params()->fromQuery('id'); + $id = $this->params()->fromRoute('id'); $this->postService->deletePost($id); @@ -47,10 +42,9 @@ class Module return [ 'controllers' => [ 'factories' => [ - 'PostController' => function ($cpm) { - // We assume a Service key 'PostService' here that returns the PostService Class + 'PostController' => function ($container) { return new PostController( - $cpm->getServiceLocator()->get('PostService') + $container->get('PostService') ); }, ], @@ -95,9 +89,9 @@ class Module { return [ 'factories' => [ - 'PostService' => function($sm) { + 'PostService' => function($container) { return new PostService( - $sm->get('doctrine.entitymanager.orm_default') + $container->get('doctrine.entitymanager.orm_default') ); } ] @@ -121,7 +115,7 @@ Assuming the application example above we can easily use LmcRbacMvc to protect o return [ 'lmc_rbac' => [ 'guards' => [ - 'LmcRbacMvc\Guard\RouteGuard' => [ + \Lmc\Rbac\Mvc\Guard\RouteGuard::class => [ 'post/delete' => ['admin'] ] ] @@ -153,7 +147,7 @@ permissions before doing anything wrong. So let's modify our previously created ```php use Doctrine\Persistence\ObjectManager; -use LmcRbacMvc\Service\AuthorizationService; +use Lmc\Rbac\Mvc\Service\AuthorizationService; class PostService { @@ -163,10 +157,10 @@ class PostService public function __construct( ObjectManager $objectManager, - AuthorizationService $autorizationService + AuthorizationService $authorizationService ) { $this->objectManager = $objectManager; - $this->authorizationService = $autorizationService; + $this->authorizationService = $authorizationService; } public function deletePost($id) @@ -197,7 +191,7 @@ class Module 'PostService' => function($sm) { return new PostService( $sm->get('doctrine.entitymanager.orm_default'), - $sm->get('LmcRbacMvc\Service\AuthorizationService') // This is new! + $sm->get('Lmc\Rbac\Mvc\Service\AuthorizationService') // This is new! ); } ] @@ -270,7 +264,7 @@ You can quickly reject access to all admin routes using the following guard: return [ 'lmc_rbac' => [ 'guards' => [ - 'LmcRbacMvc\Guard\RouteGuard' => [ + 'Lmc\Rbac\Mvc\Guard\RouteGuard' => [ 'admin*' => ['admin'] ] ] @@ -295,10 +289,10 @@ class PostService public function __construct( ObjectManager $objectManager, - AuthorizationService $autorizationService + AuthorizationService $authorizationService ) { $this->objectManager = $objectManager; - $this->authorizationService = $autorizationService; + $this->authorizationService = $authorizationService; } public function deletePost($id) @@ -319,7 +313,7 @@ As we can see, we check within our Service if the User of our Application is all against the `deletePost` permission. Now how can we achieve that only a user who is the owner of the Post to be able to delete his own post, but other users can't? We do not want to change our Service with more complex logic because this is not the task of such service. The Permission-System should handle this. And we can, for this we have the - `AssertionPluginManager` and here is how to do it: +`AssertionPluginManager` and here is how to do it: First of all we need to write an Assertion. The Assertion will return a boolean statement about the current identity being the owner of the post. @@ -327,8 +321,8 @@ identity being the owner of the post. ```php namespace Your\Namespace; -use LmcRbacMvc\Assertion\AssertionInterface; -use LmcRbacMvc\Service\AuthorizationService; +use Lmc\Rbac\Mvc\Assertion\AssertionInterface; +use Lmc\Rbac\Mvc\Service\AuthorizationService; class MustBeAuthorAssertion implements AssertionInterface { @@ -448,8 +442,8 @@ The assertion must therefore be modified like this: ```php namespace Your\Namespace; -use LmcRbacMvc\Assertion\AssertionInterface; -use LmcRbacMvc\Service\AuthorizationService; +use Lmc\Rbac\Mvc\Assertion\AssertionInterface; +use Lmc\Rbac\Mvc\Service\AuthorizationService; class MustBeAuthorAssertion implements AssertionInterface { @@ -507,11 +501,11 @@ In this last example, the menu item will be hidden for users who don't have the ## Using LmcRbacMvc with Doctrine ORM -First your User entity class must implement `LmcRbacMvc\Identity\IdentityInterface` : +First your User entity class must implement `Lmc\Rbac\Mvc\Identity\IdentityInterface` : ```php use LmccUser\Entity\User as LmcUserEntity; -use LmcRbacMvc\Identity\IdentityInterface; +use Lmc\Rbac\Mvc\Identity\IdentityInterface; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; @@ -721,47 +715,4 @@ public function hasPermission($permission) > NOTE: This is only supported starting from Doctrine ORM 2.5! -## Using LmcRbacMvc and ZF2 Assetic - -To use [Assetic](https://github.com/widmogrod/zf2-assetic-module) with LmcRbacMvc guards, you should modify your -`module.config.php` using the following configuration: - -```php -return [ - 'assetic_configuration' => [ - 'acceptableErrors' => [ - \LmcRbacMvc\Guard\GuardInterface::GUARD_UNAUTHORIZED - ] - ] -]; -``` - -## Using LmcRbacMvc and LmcUser -To use the authentication service from LmcUser, just add the following alias in your application.config.php: - -```php -return [ - 'service_manager' => [ - 'aliases' => [ - 'Laminas\Authentication\AuthenticationService' => 'lmcuser_auth_service' - ] - ] -]; -``` - -Finally add the LmcUser routes to your `guards`: - -```php -return [ - 'lmc_rbac' => [ - 'guards' => [ - 'LmcRbac\Guard\RouteGuard' => [ - 'lmcuser/login' => ['guest'], - 'lmcuser/register' => ['guest'], // required if registration is enabled - 'lmcuser*' => ['user'] // includes logout, changepassword and changeemail - ] - ] - ] -]; -``` diff --git a/docs/versioned_docs/version-4.0/Guides/identity-providers.md b/docs/versioned_docs/version-4.0/Guides/identity-providers.md new file mode 100644 index 00000000..e910eb9f --- /dev/null +++ b/docs/versioned_docs/version-4.0/Guides/identity-providers.md @@ -0,0 +1,25 @@ +--- +title: Create a custom identity provider +sidebar_label: Custom Identity Providers +sidebar_position: 2 +--- + +Identity providers return the current identity. Most of the time, this means the logged in user. LmcRbacMvc comes with a +default identity provider (`Lmc\Rbac\Mvc\Identity\AuthenticationIdentityProvider`) that uses the +`Laminas\Authentication\AuthenticationService` service. + +### Create your own identity provider + +If you want to implement your own identity provider, create a new class that implements +`Lmc\Rbac\Mvc\Identity\IdentityProviderInterface` class. Then, change the `identity_provider` option in LmcRbacMvc config, +as shown below: + +```php +return [ + 'lmc_rbac' => [ + 'identity_provider' => 'MyCustomIdentityProvider' + ] +]; +``` + +The identity provider is automatically pulled from the service manager. diff --git a/docs/versioned_docs/version-4.0/Guides/images/guards.png b/docs/versioned_docs/version-4.0/Guides/images/guards.png new file mode 100644 index 00000000..c008496e Binary files /dev/null and b/docs/versioned_docs/version-4.0/Guides/images/guards.png differ diff --git a/docs/versioned_docs/version-4.0/Guides/images/roles.png b/docs/versioned_docs/version-4.0/Guides/images/roles.png new file mode 100644 index 00000000..559a4709 Binary files /dev/null and b/docs/versioned_docs/version-4.0/Guides/images/roles.png differ diff --git a/docs/versioned_docs/version-4.0/Guides/images/settings.png b/docs/versioned_docs/version-4.0/Guides/images/settings.png new file mode 100644 index 00000000..bdefb23f Binary files /dev/null and b/docs/versioned_docs/version-4.0/Guides/images/settings.png differ diff --git a/docs/versioned_docs/version-4.0/Guides/lmcuser.md b/docs/versioned_docs/version-4.0/Guides/lmcuser.md new file mode 100644 index 00000000..c9b33bfb --- /dev/null +++ b/docs/versioned_docs/version-4.0/Guides/lmcuser.md @@ -0,0 +1,119 @@ +--- +title: Using LmcRbacMvc and LmcUser +sidebar_label: Using LmcRbacMvc and LmcUser +sidebar_position: 3 +--- + +To use the authentication service from LmcUser, there are a few actions to take: + +1. Set up a user entity that supports roles +2. Set up the Laminas authentication service to use LmcUser +3. Set up guards +4. Optionally, set up a redirect strategy + +## Set up the user entity + +The default user entity class in LmcUser does not implement the `Lmc\Rbac\Identity\IdentityInterface`. You will need +to define a user identity class that does by, for example, extending the default user class: + +```php +roles; + } + + public function setRoles(array $roles): User + { + $this->roles = $roles; + return $this; + } +} +```` + +and then set LmcUser to use this entity: + +```php +return [ + 'lmc_user' => [ + 'user_entity_class' => CustomUser::class, + ] +]; +``` +:::note +This example does not cover modifying the database tables and mappers to fetch/hydrate roles into the user object. +::: + +## Set up the Laminas authentication service to use LmcUser + +You need to set up Laminas Authentication to use the Authentication service from LmcUser. + +Add the following alias in your `application.config.php`: + +```php +return [ + 'service_manager' => [ + 'aliases' => [ + 'Laminas\Authentication\AuthenticationService' => 'lmcuser_auth_service' + ] + ] +]; +``` + +## Set up guards + +The login and register pages should be only accessible from 'guest' users and all other pages should be accessible from +logged in users. + +Add the LmcUser routes to your `guards`: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + \Lmc\Rbac\Mvc\Guard\RouteGuard::class => [ + 'lmcuser/login' => ['guest'], + 'lmcuser/register' => ['guest'], // required if registration is enabled + 'lmcuser*' => ['user'] // includes logout, changepassword and changeemail + ] + ] + ] +]; +``` + +## Set up a redirect strategy + +If you would like for your application to redirect users to the login page when an unauthorized access is detected, then +you need to setup the `RedirectStrategy`: + +In your application.config.php: +```php + +return [ + 'listeners' => [ + \Lmc\Rbac\Mvc\View\Strategy\RedirectStrategy::class, + ], +]; +``` + +In your LmcRbac config file + +```php +return [ + 'lmc_rbac' => [ + 'redirect_strategy' => [ + 'redirect_when_connected' => true, + 'redirect_to_route_connected' => 'home', + 'redirect_to_route_disconnected' => 'lmcuser/login', + 'append_previous_uri' => true, + 'previous_uri_query_key' => 'redirectTo' + ], + ] +]; +``` + diff --git a/docs/versioned_docs/version-4.0/Upgrading/upgrade.md b/docs/versioned_docs/version-4.0/Upgrading/upgrade.md new file mode 100644 index 00000000..33be67bf --- /dev/null +++ b/docs/versioned_docs/version-4.0/Upgrading/upgrade.md @@ -0,0 +1,4 @@ +--- +title: Upgrading from v3 to v4 +sidebar_label: From v3 to v4 +--- diff --git a/docs/versioned_docs/version-4.0/configuration.md b/docs/versioned_docs/version-4.0/configuration.md new file mode 100644 index 00000000..7c2f6668 --- /dev/null +++ b/docs/versioned_docs/version-4.0/configuration.md @@ -0,0 +1,25 @@ +--- +sidebar_label: Configuration +sidebar_position: 5 +title: Configuring LmcRbacMvc +--- + +LmcRbacMvc is configured via the `lmc_rbac` key in the application config. + +This is typically achieved by creating +a `config/autoload/lmcrbac.global.php` file. A sample configuration file is provided in the `config/` folder. + +:::warning +LmcRbacMvc and LmcRbac share the same config key `'lmc_rbac'`. This allow to configure LmcRbacMvc by adding its specific +configs to the same configuration file as LmcRbac. +::: + +## Reference + +| Key | Type | Values | Description | +|-------------------------|----------------------|------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `guards` | array | `[]` | Defines the guards to implement.
Refer to the section on [Guards](guards.md). | +| 'protection_policy' | string | - `GuardInterface::POLICY_ALLOW` **(default)**
- `GuardInterface::POLICY_DENY` | Defines the protection policy that guards will use when no rules are specified for the role.
Refer to the [Guards](guards.md#protection-policy) section. | +| 'unauthorized_strategy' | array map\|null | Defaults to `null` | Defines the configuration for the UnAuthorized strategy.
Refer to the [Unauthorized Strategy](strategies#unauthorizedstrategy) section. | +| 'redirect_strategy' | array map\|null | Defaults to `null` | Defines the configuration for the Redirect strategy.
Refer to the [Redirect Strategy](strategies#redirectstrategy) section. | +| 'guard_manager' | array map | `[]` **(default)** | Guard Manager Plugin Manager configuration.
Must follow a Service Manager configuration. | diff --git a/docs/versioned_docs/version-4.0/guards.md b/docs/versioned_docs/version-4.0/guards.md new file mode 100644 index 00000000..111050ff --- /dev/null +++ b/docs/versioned_docs/version-4.0/guards.md @@ -0,0 +1,477 @@ +--- +sidebar_position: 2 +title: Guards +--- +In this section, you will learn: + +* What guards are +* How to use and configure built-in guards +* How to create custom guards + +## What are guards and when should you use them? + +Guards are listeners that are registered on a specific event of +the MVC workflow. They allow your application to quickly mark a request as unauthorized. + +Here is a simple workflow without guards: + +![Laminas Framework workflow without guards](images/workflow-without-guards.png?raw=true) + +And here is a simple workflow with a route guard: + +![Laminas Framework workflow with guards](images/workflow-with-guards.png?raw=true) + +RouteGuard and ControllerGuard are not aware of permissions but rather only think about "roles". For +instance, you may want to refuse access to each routes that begin by "admin/*" to all users that do not have the +"admin" role. + +If you want to protect a route for a set of permissions, you must use RoutePermissionsGuard. For instance, +you may want to grant access to a route "post/delete" only to roles having the "delete" permission. +Note that in a RBAC system, a permission is linked to a role, not to a user. + +Albeit simple to use, guards should not be the only protection in your application, and you should always +protect your services as well. The reason is that your business logic should be handled by your service. Protecting a given +route or controller does not mean that the service cannot be access from elsewhere (another action for instance). + +### Protection policy + +By default, when a guard is added, it will perform a check only on the specified guard rules. Any route or controller +that is not specified in the rules will be "granted" by default. Therefore, the default is a "blacklist" +mechanism. + +However, you may want a more restrictive approach (also called "whitelist"). In this mode, once a guard is added, +anything that is not explicitly added will be refused by default. + +For instance, let's say you have two routes: "index" and "login". If you specify a route guard rule to allow "index" +route to "member" role, your "login" route will become defacto unauthorized to anyone, unless you add a new rule for +allowing the route "login" to "member" role. + +You can change it in LmcRbacMvc config, as follows: + +```php +use LmcRbacMvc\Guard\GuardInterface; + +return [ + 'lmc_rbac' => [ + 'protection_policy' => GuardInterface::POLICY_DENY + ] +]; +``` + +> NOTE: this policy will block ANY route/controller (so it will also block any console routes or controllers). The +deny policy is much more secure, but it needs much more configuration to work with. + +## Built-in guards + +LmcRbacMvc comes with four guards, in order of priority : + +* RouteGuard : protect a set of routes based on the identity roles +* RoutePermissionsGuard : protect a set of routes based on roles permissions +* ControllerGuard : protect a controllers and/or actions based on the identity roles +* ControllerPermissionsGuard : protect a controllers and/or actions based on roles permissions + +All guards must be added in the `guards` subkey: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + // Guards config here! + ] + ] +]; +``` + +Because of the way Laminas Framework handles config, you can without problem define some rules in one module, and +more rules in another module. All the rules will be automatically merged. + +> For your mental health, I recommend you to use either the route guard OR the controller guard, but not both. If +you decide to use both conjointly, I recommend you to set the protection policy to "allow" (otherwise, you will +need to define rules for every routes AND every controller, which can become quite frustrating!). + +Please note that if your application uses both route and controller guards, route guards are always executed +**before** controller guards (they have a higher priority). + +### RouteGuard + +> The RouteGuard listens to the `MvcEvent::EVENT_ROUTE` event with a priority of -5. + +The RouteGuard allows your application to protect a route or a hierarchy of routes. You must provide an array of "key" => "value", +where the key is a route pattern and the value is an array of role names: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\RouteGuard' => [ + 'admin*' => ['admin'], + 'login' => ['guest'] + ] + ] + ] +]; +``` + +> Only one role in a rule needs to be matched (it is an OR condition). + +Those rules grant access to all admin routes to users that have the "admin" role, and grant access to the "login" +route to users that have the "guest" role (eg.: most likely unauthenticated users). + +> The route pattern is not a regex. It only supports the wildcard (*) character, that replaces any segment. + +You can also use the wildcard character * for roles: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\RouteGuard' => [ + 'home' => ['*'] + ] + ] + ] +]; +``` + +This rule grants access to the "home" route to anyone. + +Finally, you can also omit the roles array to completely block a route, for maintenance purpose for example : + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\RouteGuard' => [ + 'route_under_construction' + ] + ] + ] +]; +``` + +This rule will be inaccessible. + +Note : this last example could be (and should be) written in a more explicit way : + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\RouteGuard' => [ + 'route_under_construction' => [] + ] + ] + ] +]; +``` + + +### RoutePermissionsGuard + +> The RoutePermissionsGuard listens to the `MvcEvent::EVENT_ROUTE` event with a priority of -8. + +The RoutePermissionsGuard allows your application to protect a route or a hierarchy of routes. You must provide an array of "key" => "value", +where the key is a route pattern and the value is an array of permission names: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\RoutePermissionsGuard' => [ + 'admin*' => ['admin'], + 'post/manage' => ['post.update', 'post.delete'] + ] + ] + ] +]; +``` + +> By default, all permissions in a rule must be matched (an AND condition). + +In the previous example, one must have ```post.update``` **AND** ```post.delete``` permissions +to access the ```post/manage``` route. You can also specify an OR condition like so: + +```php +use LmcRbacMvc\Guard\GuardInterface; + +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\RoutePermissionsGuard' => [ + 'post/manage' => [ + 'permissions' => ['post.update', 'post.delete'], + 'condition' => GuardInterface::CONDITION_OR + ] + ] + ] + ] +]; +``` + +> Permissions are linked to roles, not to users + +Those rules grant access to all admin routes to roles that have the "admin" permission, and grant access to the +"post/delete" route to roles that have the "post.delete" or "admin" permissions. + +> The route pattern is not a regex. It only supports the wildcard (*) character, that replaces any segment. + +You can also use the wildcard character * for permissions: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\RoutePermissionsGuard' => [ + 'home' => ['*'] + ] + ] + ] +]; +``` + +This rule grants access to the "home" route to anyone. + +Finally, you can also use an empty array to completly block a route, for maintenance purpose for example : + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\RoutePermissionsGuard' => [ + 'route_under_construction' => [] + ] + ] + ] +]; +``` + +This route will be inaccessible. + + +### ControllerGuard + +> The ControllerGuard listens to the `MvcEvent::EVENT_ROUTE` event with a priority of -10. + +The ControllerGuard allows your application to protect a controller. You must provide an array of arrays: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\ControllerGuard' => [ + [ + 'controller' => 'MyController', + 'roles' => ['guest', 'member'] + ] + ] + ] + ] +]; +``` + +> Only one role in a rule need to be matched (it is an OR condition). + +Those rules grant access to each actions of the MyController controller to users that have either the "guest" or +"member" roles. + +As for RouteGuard, you can use a wildcard (*) character for roles. + +You can also specify optional actions, so that the rule only apply to one or several actions: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\ControllerGuard' => [ + [ + 'controller' => 'MyController', + 'actions' => ['read', 'edit'], + 'roles' => ['guest', 'member'] + ] + ] + ] + ] +]; +``` + +You can combine a generic rule and a specific action rule for the same controller, as follows: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\ControllerGuard' => [ + [ + 'controller' => 'PostController', + 'roles' => ['member'] + ], + [ + 'controller' => 'PostController', + 'actions' => ['delete'], + 'roles' => ['admin'] + ] + ] + ] + ] +]; +``` + +These rules grant access to each controller action to users that have the "member" role, but restrict the +"delete" action to "admin" only. + +### ControllerPermissionsGuard + +> The ControllerPermissionsGuard listens to the `MvcEvent::EVENT_ROUTE` event with a priority of -13. + +The ControllerPermissionsGuard allows your application to protect a controller using permissions. You must provide an array of arrays: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'LmcRbacMvc\Guard\ControllerPermissionsGuard' => [ + [ + 'controller' => 'MyController', + 'permissions' => ['post.update', 'post.delete'] + ] + ] + ] + ] +]; +``` + +> All permissions in a rule must be matched (it is an AND condition). + +In the previous example, the user must have ```post.update``` **AND** ```post.delete``` permissions +to access each action of the MyController controller. + +As for all other guards, you can use a wildcard (*) character for permissions. + +The configuration rules are the same as for ControllerGuard. + +### Security notice + +RouteGuard and ControllerGuard listen to the `MvcEvent::EVENT_ROUTE` event. Therefore, if you use the +`forward` method in your controller, those guards will not intercept and check requests (because internally +Laminas MVC does not trigger again a new MVC loop). + +Most of the time, this is not an issue, but you must be aware of it, and this is an additional reason why you +should always protect your services too. + +## Creating custom guards + +LmcRbacMvc is flexible enough to allow you to create custom guards. Let's say we want to create a guard that will +refuse access based on an IP addresses blacklist. + +First create the guard: + +```php +namespace Application\Guard; + +use Laminas\Http\Request as HttpRequest; +use Laminas\Mvc\MvcEvent; +use LmcRbacMvc\Guard\AbstractGuard; + +class IpGuard extends AbstractGuard +{ + const EVENT_PRIORITY = 100; + + /** + * List of IPs to blacklist + */ + protected $ipAddresses = []; + + /** + * @param array $ipAddresses + */ + public function __construct(array $ipAddresses) + { + $this->ipAddresses = $ipAddresses; + } + + /** + * @param MvcEvent $event + * @return bool + */ + public function isGranted(MvcEvent $event) + { + $request = $event->getRequest(); + + if (!$request instanceof HttpRequest) { + return true; + } + + $clientIp = $_SERVER['REMOTE_ADDR']; + + return !in_array($clientIp, $this->ipAddresses); + } +} +``` + +> Guards must implement `LmcRbacMvc\Guard\GuardInterface`. + +By default, guards are listening to the event `MvcEvent::EVENT_ROUTE` with a priority of -5 (you can change the default +event to listen by overriding the `EVENT_NAME` constant in your guard subclass). However, in this case, we don't +even need to wait for the route to be matched, so we overload the `EVENT_PRIORITY` constant to be executed earlier. + +The `isGranted` method simply retrieves the client IP address, and checks it against the blacklist. + +However, for this to work, we must register the newly created guard with the guard plugin manager. To do so, add the +following code in your config: + +```php +return [ + 'lmc_rbac' => [ + 'guard_manager' => [ + 'factories' => [ + 'Application\Guard\IpGuard' => 'Application\Factory\IpGuardFactory' + ] + ] + ] +]; +``` + +The `guard_manager` config follows a conventional service manager configuration format. + +Now, let's create the factory: + +```php +namespace Application\Factory; + +use Application\Guard\IpGuard; +use Laminas\ServiceManager\Factory\FactoryInterface; +use Laminas\ServiceManager\ServiceLocatorInterface; + +class IpGuardFactory implements FactoryInterface +{ + /** + * {@inheritDoc} + */ + public function __invoke(ContainerInterface $container, $requestedName, array $options = null) + { + if (null === $options) { + $options = []; + } + return new IpGuard($options); + } +} +``` + +In a real use case, you would likely fetched the blacklist from a database. + +Now we just need to add the guard to the `guards` option, so that LmcRbacMvc can execute the logic behind this guard. In +your config, add the following code: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'Application\Guard\IpGuard' => [ + '87.45.66.46', + '65.87.35.43' + ] + ] + ] +]; +``` +The array of IP addresses will be passed to `IpGuardFactory::__invoke` in the `$options` parameter. diff --git a/docs/versioned_docs/version-4.0/images/workflow-with-guards.png b/docs/versioned_docs/version-4.0/images/workflow-with-guards.png new file mode 100644 index 00000000..3c3d2179 Binary files /dev/null and b/docs/versioned_docs/version-4.0/images/workflow-with-guards.png differ diff --git a/docs/versioned_docs/version-4.0/images/workflow-without-guards.png b/docs/versioned_docs/version-4.0/images/workflow-without-guards.png new file mode 100644 index 00000000..fd49abad Binary files /dev/null and b/docs/versioned_docs/version-4.0/images/workflow-without-guards.png differ diff --git a/docs/versioned_docs/version-4.0/intro.md b/docs/versioned_docs/version-4.0/intro.md new file mode 100644 index 00000000..0a0fb3af --- /dev/null +++ b/docs/versioned_docs/version-4.0/intro.md @@ -0,0 +1,218 @@ +--- +title: Getting Started +sidebar_label: Getting Started +sidebar_position: 1 +--- + +LmcRbacMvc is a companion component that extends the functionality of LmcRbac to provide Role-based Access Control +(RBAC) for Laminas MVC applications. + +LmcRbacMvc provides additional features on top of LmcRbac that are suitable for a Laminas MVC application: + +- Guards that acts like a firewall allowing access to routes, controllers and actions to authorized users. +- Strategies to execute when unauthorized access occurs such as redirection and error responses +- Extensions to LmcRbac Authorization service such as controller and view plugins + +:::tip[Important Note:] + +If you are migrating from v3, there are breaking changes to take into account. See the [Upgrading](Upgrading/upgrade.md) section for details. +::: + +## Extending LmcRbac + +LmcRbacMvc extends the functionality of LmcRbac to support Laminas MVC applications. + +It is highly recommended to first go through the concepts and usage of LmcRbac before using the functionalities of +LmcRbacMvc. + + + +## Requirements + +- PHP 8.1 or higher +- LmcRbac v2 (installed by default) + +### Optional requirements + +- [LmcRbacMvcDeveloperTools](https://github.com/LM-Commons/LmcRbacMvcDeveloperTools): a companion component to Laminas Developer Tools to collect and display LmcRbcMvc data + +## Installation + +Install the module using Composer: + +```sh +$ composer require lm-commons/lmc-rbac-mvc:^4.0 +``` + +You will be prompted by the `laminas-component-installer` plugin to inject LM-Commons\LmcRbacMvc. + +:::note[Manual installation] + +Enable the module by adding `Lmc\Rbac\Mvc` key to your `application.config.php` or `modules.config.php` file. +::: + +Customize the module by copy-pasting the `lmc_rbac.global.php.dist` file to your `config/autoload` folder. + +:::warning +LmcRbac and LmcRbacMvc share the same config key `'lmc_rbac'`. Be careful when creating configuration files to avoid +overriding configuration. + +It is recommended that have one configuration file containing both LmcRbac and LmcRbacMvc configuration. This makes it +easier to keep all configuration in one place. +::: + +## Quick Start + +Before you start configuring LmcRbacMvc, you must set up LmcRbac first. Please follow the [instructions](https://lm-commons.github.io/LmcRbac/docs/gettingstarted) in LmcRbac +documentation. + +### Specifying an identity provider + +By default, LmcRbacMvc internally uses the `Laminas\Authentication\AuthenticationService` service key to retrieve the user (logged or +not). Therefore, you must implement and register this service in your application by providing a factory on your configuration. + +For example, in `module.config.php` file: + +```php +return [ + 'service_manager' => [ + 'factories' => [ + \Laminas\Authentication\AuthenticationService::class => function($container) { + // Create your authentication service! + } + ] + ] +]; +``` + +The identity given by `Laminas\Authentication\AuthenticationService` must implement `Lmc\Rbac\Identity\IdentityInterface`. + +:::warning +Note that the default identity provided with Laminas does not implement this interface. +::: + +:::tip +If you are also using the [LmcUser](https://github.com/lm-commons/lmcuser) package, then the `Laminas\Authentication\AuthenticationService` will be +provided for you and there is no need to implement your own. + +:::warning +LmcUser's default User entity does not implement the `IdentityInteface` that is required +by LmcRbac. +::: + +LmcRbacMvc is flexible enough to use something other than the built-in `AuthenticationService`, by specifying custom +identity providers. For more information, refer to the [Create a custom identity provider](Guides/identity-providers.md) +section. + +## Adding a guard + +A guard allows your application to block access to routes and/or controllers using a simple syntax. For instance, this configuration +grants access to any route that begins with `admin` (or is exactly `admin`) to the `admin` role only: + +```php +return [ + 'lmc_rbac' => [ + 'guards' => [ + 'Lmc\Rbac\Mvc\Guard\RouteGuard' => [ + 'admin*' => ['admin'] + ] + ] + ] +]; +``` + +LmcRbacMvc has several built-in guards, and you can also register your own guards. For more information, refer +[to this section](guards.md#built-in-guards). + +## Registering a strategy + +When a guard blocks access to a route/controller, or if you throw the `Lmc\Rbac\Mvc\Exception\UnauthorizedException` +exception in your service, LmcRbacMvc automatically performs some logic for you depending on the view strategy used. + +For instance, if you want LmcRbacMvc to automatically redirect all unauthorized requests to the "login" route, +add +the following code in the `onBootstrap` method of your `Module.php` class: + +```php +public function onBootstrap(MvcEvent $event) +{ + $app = $event->getApplication(); + $sm = $app->getServiceManager(); + $em = $app->getEventManager(); + + $listener = $sm->get(\Lmc\Rbac\Mvc\View\Strategy\RedirectStrategy::class); + $listener->attach($em); +} +``` + +or add the listener to 'listeners' config key in a configuration file: + +```php +return [ + // other configs... + + 'listeners' => [ + \Lmc\Rbac\Mvc\View\Strategy\RedirectStrategy::class + ], +]; +``` + + +By default, `RedirectStrategy` redirects all unauthorized requests to a route named "login" when the user is not connected +and to a route named "home" when the user is connected. This is entirely configurable. + +:::warning +For flexibility purposes, LmcRbacMvc **does not** register any strategy for you by default! +::: + +For more information about built-in strategies, refer [to this section](strategies.md#built-in-strategies) +in the [Strategies](strategies.md) section. + +## Using the authorization service + +With LmcRbac and LmcRbacMvc properly configured, you can inject the authorization service into any class and use it to +check if the current identity is granted to do something. + +The LmcRbacMvc Authorization Service is a wrapper to the LmcRbac Authorization Service. + +The difference is in the `isGranted` method: + +```php +public function isGranted(string $permission, mixed $context = null): bool; +``` +where the service will get the identity from the identity provider and there is no need to get it separately. + +The authorization service can be retrieved from the container using the key `Lmc\Rbac\Mvc\Service\AuthorizationServiceInterface`. +Once injected, you can use it as follows: + +```php +use Lmc\Rbac\Mvc\Exception\UnauthorizedException; + +class ActionController extends \Laminas\Mvc\Controller\AbstractActionController { +public function delete() +{ + if (!$this->authorizationService->isGranted('delete')) { + throw new UnauthorizedException(); + } + + // Delete the post +} +} +``` diff --git a/docs/versioned_docs/version-4.0/plugins.md b/docs/versioned_docs/version-4.0/plugins.md new file mode 100644 index 00000000..59d61a58 --- /dev/null +++ b/docs/versioned_docs/version-4.0/plugins.md @@ -0,0 +1,51 @@ +--- +sidebar_position: 5 +--- + +# Plugins and Helpers + +LmcRbacMvc provides a controller plugin and view helpers to check authorization. + + +## Controller plugins + +#### `isGranted(string $permission, $context=null): bool` + +Basic usage: + +```php + public function doSomethingAction() + { + if (!$this->isGranted('myPermission', $context)) { + // redirect if not granted for example + } + } +``` + +## View Helpers + +#### `isGranted(string $permission, $context=null): bool` + +Basic usage: + +```php + isGranted('myPermission', $myContext)): ?> +
+

Display only if granted

+
+ +``` + +#### `hasRole(array $roleOrRoles): bool` + +Basic usage: + +```php + hasRole(['admin'])): ?> +
+

Display only if user has the admin role

+
+ +``` + + diff --git a/docs/versioned_docs/version-4.0/strategies.md b/docs/versioned_docs/version-4.0/strategies.md new file mode 100644 index 00000000..da41c80c --- /dev/null +++ b/docs/versioned_docs/version-4.0/strategies.md @@ -0,0 +1,143 @@ +--- +title: Strategies +sidebar_position: 3 +--- + +## What are strategies? + +A strategy is an object that listens to the `MvcEvent::EVENT_DISPATCH_ERROR` event. It is used to describe what +happens when access to a resource is unauthorized by LmcRbacMvc. + +LmcRbacMvc strategies all check if an `Lmc\Rbac\Mvc\Exception\UnauthorizedExceptionInterface` has been thrown. + +By default, LmcRbacMvc does not register any strategy for you. The best place to register it in a config file under the +`'listeners'` key: + +```php +return [ + // other configs... + + 'listeners' => [ + \Lmc\Rbac\Mvc\View\Strategy\UnauthorizedStrategy::class + ], +]; +``` +## Built-in strategies + +LmcRbacMvc comes with two built-in strategies: +- `\Lmc\Rbac\Mvc\View\Strategy\RedirectStrategy` +- `\Lmc\Rbac\Mvc\View\Strategy\UnauthorizedStrategy`. + +### RedirectStrategy + +This strategy allows your application to redirect any unauthorized request to another route by optionally appending the previous +URL as a query parameter. + +To register it, copy-paste this code into a configuration file: + +```php +return [ + // other configs... + + 'listeners' => [ + \Lmc\Rbac\Mvc\View\Strategy\RedirectStrategy::class + ], +]; +``` + +You can configure the strategy using the `redirect_strategy` subkey: + +```php +return [ + 'lmc_rbac' => [ + 'redirect_strategy' => [ + 'redirect_when_connected' => true, + 'redirect_to_route_connected' => 'home', + 'redirect_to_route_disconnected' => 'login', + 'append_previous_uri' => true, + 'previous_uri_query_key' => 'redirectTo' + ], + ] +]; +``` + +If users try to access an unauthorized resource (eg.: http://www.example.com/delete), they will be +redirected to the "login" route if is not connected and to the "home" route otherwise with the previous URL appended: + +> http://www.example.com/login?redirectTo=http://www.example.com/delete + +You can prevent redirection when a user is connected (i.e. so that the user gets a 403 page) by setting `redirect_when_connected` to `false`. + +### UnauthorizedStrategy + +This strategy allows your application to render a template on any unauthorized request. + +To register it, copy-paste this code into your Module.php class: + +```php +return [ + // other configs... + + 'listeners' => [ + \Lmc\Rbac\Mvc\View\Strategy\UnauthorizedStrategy::class + ], +]; +``` + +You can configure the strategy using the `unauthorized_strategy` subkey: + +```php +return [ + 'lmc_rbac' => [ + 'unauthorized_strategy' => [ + 'template' => 'error/custom-403' + ], + ] +]; +``` + +> By default, LmcRbacMvc uses a template called `error/403`. + +## Creating custom strategies + +Creating a custom strategy is rather easy. Let's say we want to create a strategy that integrates with +the [ApiProblem](https://github.com/laminas-api-tools/api-tools-api-problem) Laminas Api Tools module: + +```php +namespace Application\View\Strategy; + +use Laminas\Http\Response as HttpResponse; +use Laminas\Mvc\MvcEvent; +use Laminas\ApiTools\ApiProblem\ApiProblem; +use Laminas\ApiTools\ApiProblem\ApiProblemResponse; +use Lmc\Rbac\Mvc\View\Strategy\AbstractStrategy; +use Lmc\Rbac\Mvc\Exception\UnauthorizedExceptionInterface; + +class ApiProblemStrategy extends AbstractStrategy +{ + public function onError(MvcEvent $event) + { + // Do nothing if no error or if response is not HTTP response + if (!($exception = $event->getParam('exception') instanceof UnauthorizedExceptionInterface) + || ($result = $event->getResult() instanceof HttpResponse) + || !($response = $event->getResponse() instanceof HttpResponse) + ) { + return; + } + + return new ApiProblemResponse(new ApiProblem($exception->getMessage())); + } +} +``` + +Register your strategy: + +```php +return [ + // other configs... + + 'listeners' => [ + Application\View\Strategy\ApiProblemStrategy::class, + ], +]; +``` diff --git a/docs/versioned_docs/version-4.0/using-the-authorization-service.md b/docs/versioned_docs/version-4.0/using-the-authorization-service.md new file mode 100644 index 00000000..adc3bb96 --- /dev/null +++ b/docs/versioned_docs/version-4.0/using-the-authorization-service.md @@ -0,0 +1,39 @@ +--- +sidebar_position: 4 +sidebar_label: Authorization Service +--- +# Using the Authorization Service + +The LmcRbacMvc Authorization service is a wrapper for the LmcRbac Authorization service. + +`\Lmc\Rbac\Mvc\Service\AuthorizationService` provides the same methods as `\Lmc\Rbac\Service\AuthorizationService` +except for the `isGranted()` method which does not required an identity parameter. + +`\Lmc\Rbac\Mvc\Service\AuthorizationService::isGranted()` will get the identity from the +Laminas Authentication Service directly. + +## Injecting the Authorization Service + +Different techniques for injecting the Authorization Service are described in LmcRbac. The same techniques apply +to LmcRbacMvc using the equivalent wrapper classes and trait: + +- `\Lmc\Rbac\Mvc\Service\AuthorizationServiceAwareInterface` +- `\Lmc\Rbac\Mvc\Service\AuthorizationServiceAwareTrait` +- `\Lmc\Rbac\Mvc\Service\AuthorizationServiceDelegatorFactory` + +Refer to this section in LmcRbac on how to inject the Authorization Service. + +## Permissions and Assertions + +Assertions are provided by LmcRbac. Refer to the Assertion section in LmcRbac on how to configure assertions. + +`\Lmc\Rbac\Mvc\Service\AuthorizationService` provides the same methods as `\Lmc\Rbac\Service\AuthorizationService` to +override assertions at run-time. + +:::warning +If you are upgrading from v3, please not that assertions must now implement the +`Lmc\Rbac\Assertion\AssertionInterface` interface which has a different signature for the `assert()` method. + +Make sure to update your assertions to follow the `Lmc\Rbac\Assertion\AssertionInterface` interface. +::: + diff --git a/docs/versioned_sidebars/version-4.0-sidebars.json b/docs/versioned_sidebars/version-4.0-sidebars.json new file mode 100644 index 00000000..caea0c03 --- /dev/null +++ b/docs/versioned_sidebars/version-4.0-sidebars.json @@ -0,0 +1,8 @@ +{ + "tutorialSidebar": [ + { + "type": "autogenerated", + "dirName": "." + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index f7ee0375..c0952cec 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,3 +1,4 @@ [ + "4.0", "3.4" ]