dkx / security

此包已被弃用且不再维护。未建议替代包。

安全包

0.0.2 2019-06-26 12:03 UTC

This package is auto-updated.

Last update: 2024-01-26 22:09:35 UTC


README

基于 symfony 安全和为无状态应用程序的投票者的 PHP 安全包。

安装

$ composer require dkx/security

用法

<?php

use DKX\Security\Security;
use DKX\Security\Identity\AuthenticatedIdentity;

$security = new Security;
$identity = new AuthenticatedIdentity($user, ['ROLE_ADMIN']);

$security->authenticate($identity);

var_dump($security->getIdentity());

身份验证

简单的身份验证可以在上面的示例中看到。

调用 getIdentity() 将始终返回一些身份(接口 Identity)。对于未认证的用户,它将是 GuestIdentity

您可以轻松创建自定义身份类。唯一的要求是该类必须实现 Identity 接口。

检查权限

<?php

use DKX\Security\Security;
use DKX\Security\Identity\AuthenticatedIdentity;

$security = new Security;

$security->isGranted(Security::IS_GUEST);          // true
$security->isGranted(Security::IS_AUTHENTICATED);  // false
$security->isGranted('ROLE_ADMIN');                // false

$security->authenticate(new AuthenticatedIdentity($user, ['ROLE_ADMIN']));

$security->isGranted(Security::IS_GUEST);          // false
$security->isGranted(Security::IS_AUTHENTICATED);  // true
$security->isGranted('ROLE_ADMIN');                // true

$security->logout();

$security->isGranted(Security::IS_GUEST);          // true
$security->isGranted(Security::IS_AUTHENTICATED);  // false
$security->isGranted('ROLE_ADMIN');                // false

投票者

投票者可用于进行高级权限检查。例如,它们允许检查特定用户是否可以访问特定资源。

<?php

use DKX\Security\Security;
use DKX\Security\Votes\Voter;
use DKX\Security\Identity\Identity;
use DKX\Security\Identity\GuestIdentity;

class BookVoter implements Voter
{
    public const CREATE = 'create';
    
    public function supports(string $attribute, object $subject): bool
    {
        if (!\in_array($attribute, [self::CREATE], true)) {
            return false;
        }
        
        if (!$subject instanceof Book) {
            return false;
        }
        
        return true;
    }

    public function voteOnAttribute(string $attribute, object $subject, Identity $identity): bool
    {
        if ($identity instanceof GuestIdentity) {
            return false;
        }
        
        switch ($attribute) {
            case self::CREATE: return $this->canCreate($subject, $identity);
        }
        
        // should be unreachable
        return false;
    }
    
    private function canCreate(Book $book, Identity $identity): bool 
    {
        return true;
    }
}

$security = new Security;
$security->addVoter(new BookVoter);

$security->isGranted(BookVoter::CREATE, $book);

如果您需要在投票者中访问 Security,实现 SecurityAwareVoter 接口。