如何让安全选民访问当前对象

时间:2013-06-13 13:07:30

标签: security symfony

我想使用Voter只允许所有者在我的应用程序中编辑项目对象。

我有一个route / project / 42 / edit,它调用我的动作ProjectController.editAction(Project $ project)。我使用类型提示(Project $ project)自动调用ParamConverter将ID 42从URI转换为项目对象。这适用于控制器操作,但似乎对选民来说太晚了。它的vote()方法被调用,请求作为第二个参数,而不是我的项目。

有没有办法将项目传递给选民,而无需再次从数据库中检索它?

更新:learned我必须在编辑方法的安全上下文中手动调用isGranted()。这与this answer的方法非常相似。

这是我的选民:

namespace FUxCon2013\ProjectsBundle\Security;

use FUxCon2013\ProjectsBundle\Entity\Project;
use Symfony\Component\BrowserKit\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

class OwnerVoter implements VoterInterface
{
    public function __construct(ContainerInterface $container)
    {
        $this->container     = $container;
    }

    public function supportsAttribute($attribute)
    {
        return $attribute == 'MAY_EDIT';
    }

    public function supportsClass($class)
    {
        // your voter supports all type of token classes, so return true
        return true;
    }

    function vote(TokenInterface $token, $object, array $attributes)
    {
        if (!in_array('MAY_EDIT', $attributes)) {
            return self::ACCESS_ABSTAIN;
        }
        if (!($object instanceof Project)) {
            return self::ACCESS_ABSTAIN;
        }

        $user = $token->getUser();
        $securityContext = $this->container->get('security.context');

        return $securityContext->isGranted('IS_AUTHENTICATED_FULLY')
            && $user->getId() == $object->getUser()->getId()
            ? self::ACCESS_GRANTED
            : self::ACCESS_DENIED;
    }
}

我在configure.yml中注册它,以便它将服务容器作为参数获取:

services:
    fuxcon2013.security.owner_voter:
        class:      FUxCon2013\ProjectsBundle\Security\OwnerVoter
        public:     false
        arguments: [ @service_container ]
        tags:
            - { name: security.voter }

最后一个块是将security.yml中的访问决策管理器配置为一致:

security:
    access_decision_manager:
        # strategy can be: affirmative, unanimous or consensus
        strategy: unanimous
        allow_if_all_abstain: true

2 个答案:

答案 0 :(得分:1)

请看一下我昨天写的this answer

您可以通过检查对象的所有者轻松地根据需要调整它。

答案 1 :(得分:0)

如果您使用角色安全处理程序,则当前对象不会在选民中传递。

我必须extend the latter才能得到前者。

不要犹豫,评论细节。