fivelab / authorize-action
此包已被废弃且不再维护。未建议替代包。
在执行前进行授权操作的库。
v1.0.0
2017-08-20 13:48 UTC
Requires
- php: >=7.1
- symfony/security: ~3.0
Requires (Dev)
This package is not auto-updated.
Last update: 2021-05-01 09:35:52 UTC
README
添加在执行前进行授权操作的功能。
需求
- PHP 7.1 或更高版本
安装
在您的 composer.json 中添加 AuthorizeAction 包
{ "require": { "fivelab/authorize-action": "~1.0" } }
现在运行以下命令让 composer 下载库
$ php composer.phar update fivelab/authorize-action
为什么?
在许多情况下,您应该在执行命令/代码之前检查权限。此库增加了易于声明授权操作并在执行之前验证操作的功能。
示例
首先,您应该声明授权操作。操作应该实现 FiveLab\Component\AuthorizeAction\Action\AuthorizeActionInterface
<?php namespace Application\Security; use FiveLab\Component\AuthorizeAction\Action\AuthorizeActionInterface; /** * The authorize action for check grants for edit post */ class EditPostAction implements AuthorizeActionInterface { /** * @var int */ public $id; /** * Constructor. * * @param int $postId */ public function __construct(int $postId) { $this->id = $postId; } }
其次,您应该声明用于验证此操作的验证器。验证器应该实现 FiveLab\Component\AuthorizeAction\Verifier\AuthorizeActionVerifierInterface
<?php namespace Application\Security\Verifier; use Application\Security\EditPostAction; use FiveLab\Component\AuthorizeAction\Action\AuthorizeActionInterface; use FiveLab\Component\AuthorizeAction\Verifier\AuthorizeActionVerifierInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; class EditPostVerifier implements AuthorizeActionVerifierInterface { /** * {@inheritdoc} */ public function supports(AuthorizeActionInterface $action, UserInterface $user): bool { return $action instanceof EditPostAction; } /** * {@inheritdoc} */ public function verify(AuthorizeActionInterface $action, UserInterface $user): void { if (!$user->isSuperAdmin() && !$user->isCopywriter()) { throw new AccessDeniedException(); } } }
注意:如果操作未通过验证,验证器应该抛出
AccessDeniedException
。
最后一步,您应该创建授权检查器
<?php use Application\Security\Verifier\EditPostVerifier; use FiveLab\Component\AuthorizeAction\AuthorizationChecker; use FiveLab\Component\AuthorizeAction\Verifier\AuthorizeActionVerifierChain; use FiveLab\Component\AuthorizeAction\UserProvider\SymfonyTokenStorageUserProvider; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; $tokenStorage = new TokenStorage(); $userProvider = new SymfonyTokenStorageUserProvider($tokenStorage); $verifierChain = new AuthorizeActionVerifierChain(); $verifierChain->add(new EditPostVerifier()); $authorizationChecker = new AuthorizationChecker($verifierChain, $userProvider);
太好了!创建检查器后,您可以检查执行操作的权限
$authorizationChecker->verify(new EditPostAction($postId));
注意:如果操作未通过验证(未授权),授权检查会抛出
AccessDeniedException
。
许可证
此库遵循 MIT 许可证。请参阅库中的完整许可证。
LICENSE
报告问题或功能请求
问题和功能请求在 Github 问题跟踪器 中跟踪。
贡献者
感谢所有参与此 AuthorizeAction 库开发的人!