dotkernel / dot-rbac
DotKernel RBAC授权组件
Requires
- php: ~8.1.0 || ~8.2.0 || ~8.3.0
- dotkernel/dot-authorization: ^3.4.1
- laminas/laminas-authentication: 2.16.0
- laminas/laminas-servicemanager: ^3.11
- laminas/laminas-stdlib: ^3.7
Requires (Dev)
- laminas/laminas-coding-standard: ^2.5
- phpunit/phpunit: ^10.2
- vimeo/psalm: ^5.13
README
Rbac授权模型实现了dot-authorization的AuthorizationInterface
。授权服务负责决定已认证的身份或访客是否有权访问应用程序的某些部分。
RBAC模型定义了可以分配给用户的角色。授权是基于角色而不是基于用户(如ACL中的),每个角色可以分配一个或多个权限/特权。在决定用户是否有权时,会检查所有用户角色中请求的权限,如果至少有一个角色拥有该权限,则授予访问权限。
安装
在您的项目根目录下运行以下命令
$ composer require dotkernel/dot-rbac
配置
尽管授权服务可以通过编程方式配置,但我们建议使用基于配置的方法。我们进一步描述了如何使用配置文件来配置模块。
首先,您应该通过将此包的ConfigProvider
与您的应用程序配置合并来在您的应用程序中启用该模块。这确保了所有此模块所需的依赖都已在服务管理器中注册。它还为此模块定义了默认配置值。
在您的config/autoload
文件夹中创建一个配置文件,并根据需要更改模块选项。
authorization.global.php
'dot_authorization' => [ //name of the guest role to use if no identity is provided 'guest_role' => 'guest', 'role_provider_manager' => [], //example for a flat RBAC model using the InMemoryRoleProvider 'role_provider' => [ 'type' => 'InMemory', 'options' => [ 'roles' => [ 'admin' => [ 'permissions' => [ 'edit', 'delete', //etc.. ] ], 'user' => [ 'permissions' => [ //... ] ] ] ], ], //example for a hierarchical model, less to write but it can be confusing sometimes /*'role_provider' => [ 'type' => 'InMemory', 'options' => [ 'roles' => [ 'admin' => [ 'children' => ['user'], 'permissions' => ['create', 'delete'] ], 'user' => [ 'children' => ['guest'] 'permissions' => ['edit'] ] 'guest' => [ 'permissions' => ['view'] ] ] ] ],*/ 'assertion_manager' => [ 'factories' => [ //EditAssertion::class => InvokableFactory::class, ], ], 'assertions' => [ [ 'type' => EditAssertion::class, 'permissions' => ['edit'], 'options' => [] ] ] ]
用法
每次您需要检查某人是否有权执行某些操作时,请将AuthorizationInterface::class
服务注入到您的类中,然后使用正确的参数调用isGranted
方法。有两种调用isGranted方法的方式。
第一种方法
指定您要检查的角色。
$isGranted = $this->authorizationService->isGranted($permission, $roles);
第二种方法
不指定角色或发送一个空数组作为第二个参数。这将检查已认证的身份是否有权限。
$isGranted = $this->authorizationService->isGranted($permission);
自定义IdentityProvider
每次您请求对已认证身份的授权检查时,该身份将通过注册的IdentityProviderInterface
服务提供到AuthorizationService
。
这是因为身份是依赖于认证的,所以该模块允许您根据需要覆盖此服务。如果您想从dot-authentication服务以外的其他来源获取身份,只需用您对此接口的自己的实现覆盖服务管理器中的IdentityProviderInterface::class
服务。
自定义角色提供者
通过实现RoleProviderInterface
并注册到RoleProviderPluginManager
来编写自己的角色提供者。之后,您可以在配置文件中使用它们,如上所述。
创建断言
断言在授权后、返回授权结果之前进行检查。断言可以在决定某人是否有权执行请求的操作时发挥决定性作用。一个好的断言示例可以是编辑权限,但带有限制条件,即只有当用户ID
与项目的所有者ID
匹配时才能编辑该项。您需要编写断言内的逻辑。
断言必须实现AssertionInterface
并在AssertionPluginManager
中注册。
此接口定义了以下方法
public function assert(AuthorizationInterface $authorization, $context = null);
上下文变量可以是断言为了判断授权状态所需的任何外部数据。断言必须返回一个布尔值,反映断言通过或失败的状态。