erdiko / authorize
授权功能
Requires
- php: >=5.4.0
- pimple/pimple: ~3.0
- symfony/security: ^3.2
This package is not auto-updated.
Last update: 2024-09-14 20:26:50 UTC
README
Authorize
Erdiko包,用于提供用户授权。
兼容性
此包与PHP 5.4或更高版本以及Erdiko的最新版本兼容。
安装
使用以下命令通过composer添加erdiko/authorize包
composer require erdiko/authorize
要求
在其要求中,我们依赖Pimple和Symfony Security。对于Pimple,我们选择此包来管理依赖注入,从而增加了灵活性和可扩展性。它还增加了对Symfony Security模块的兼容性。
如何使用
安装包后,您即可开始使用。基本的基于角色的管理员验证将直接工作!
要在代码中使用它,只需创建一个Authorizer
类的实例。此类将期望symfony/security包中的AuthenticationManagerInterface
实例作为构造函数参数。
以下是一个示例
class AuthenticationManager implements AuthenticationManagerInterface { private $authenticationManager; public function __construct() { // implements UserProviderInterface $userProvider = new InMemoryUserProvider( array( 'bar@mail.com' => array( 'password' => 'asdf1234', 'roles' => array('ROLE_ADMIN'), ), 'foo@mail.com' => array( 'password' => 'asdf1234', 'roles' => array('ROLE_USER'), ), ) ); // Create an encoder factory that will "encode" passwords $encoderFactory = new \Symfony\Component\Security\Core\Encoder\EncoderFactory(array( // We simply use plaintext passwords for users from this specific class 'Symfony\Component\Security\Core\User\User' => new PlaintextPasswordEncoder(), )); // The user checker is a simple class that allows to check against different elements (user disabled, account expired etc) $userChecker = new UserChecker(); // The (authentication) providers are a way to make sure to match credentials against users based on their "providerkey". $userProvider = array( new DaoAuthenticationProvider($userProvider, $userChecker, 'main', $encoderFactory, true), ); $this->authenticationManager = new AuthenticationProviderManager($userProvider, true); } public function authenticate(TokenInterface $unauthenticatedToken) { try { $authenticatedToken = $this->authenticationManager->authenticate($unauthenticatedToken); Authorizer::startSession(); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($authenticatedToken); $_SESSION['tokenstorage'] = $tokenStorage; } catch (\Exception $failed) { // authentication failed throw new \Exception($failed->getMessage()); } return $authenticatedToken; } }
将实例创建添加到_before
钩子中是最佳实践。这种最佳实践的示例如下
... public function _before() { $authManager = new AuthenticationManager(); $this->auth = new Authorizer($authManager); // Run the parent beore filter to prep the theme parent::_before(); } ...
您将有一个可用的$this->auth
属性,可以在任何get或post操作中使用。这将用于can
方法,该方法确定访问权限,允许您授予或拒绝对资源的访问。
例如,如果当前用户具有ADMIN角色,则将重定向到管理仪表板(授权),否则用户将重定向到登录页面(拒绝)。
php public function getDashboard()
{
if($this->auth->can("VIEW_ADMIN_DASHBOARD")) {
// Add page data
$this->setTitle('Erdiko Admin Dashboard');
$this->addView('examples/admin/dashboard');
} else {
\erdiko\core\helpers\FlashMessages::set("You SHALL NO Pass!!", "danger");
$this->redirect('/users/login');
}
}
请注意,在此示例中,当前用户是存储在$_SESSION['tokenstorage']
中的Symfony\Component\Security\Core\Authentication\Token\TokenInterface
实例。
还可用的是“VIEW_ADMIN_DASHBOARD”属性,我们将使用它来授予或拒绝当前用户的访问。
您可以使用相同的逻辑通过在__construct
方法中添加授权创建来验证模型
public function __construct() { $authManager = new AuthenticationManager(); $this->auth = new Authorizer($authManager); }
同样对于授权/拒绝
public function doSomething1() { if($this->auth->can("CAN_DO_1")) { return "success something one"; } else { throw new \Exception("You are not granted"); } }
定制
此包为您提供创建自定义验证的框架。有两种不同的方法来创建自定义验证
- 自定义投票者
实现Symfony\Component\Security\Core\Authorization\Voter\VoterInterface
接口,并将它们作为数组传递给Authorizer
构造函数的第二个参数。
- 自定义验证器
或者,您可以创建一个实现erdiko\authorize ValidatorInterface
接口的Validator
类。然后您需要在/app/config/default/authorize.json
中注册所有验证器,然后,您创建的所有自定义验证逻辑都将对授权器可用。
authorize.json
{ "validators":{ "custom_types": [{ "name": "example", "namespace": "app_validators_example", "classname": "ExampleValidator", "enabled": true }] } }
在这些验证器类中,您将能够定义自定义属性,“VIEW_ADMIN_DASHBOARD”如我们上面提到的,我们可能还想添加“IS_PREMIUM_ACCOUNT”,或任何其他您想要的属性。
请注意,上述JSON中的namespace
字段表示类的namespace
,它与应用程序根文件夹相关,例如/app/validators/example/ExampleValidator.php
让我们实现注册在示例JSON中的示例类。
class ExampleValidator implements ValidatorInterface { public static function supportedAttributes() { return array('IS_PREMIUM_ACCOUNT'); } public function supportsAttribute($attribute) { return in_array($attribute, self::supportedAttributes()); } public function validate($token) { $result = false; $user = $token->getUser(); if (!$user instanceof UserInterface) { $result = false; } else { $result = ($user->getRole()=='ROLE_PREMIUM'); } return $result; } }
特别感谢
Arroyo Labs - 为赞助开发,http://arroyolabs.com