Symfony Security如何运作?

时间:2013-12-30 12:40:31

标签: php symfony

请,我需要了解安全性如何工作以及是否可以覆盖。

我已经阅读了很多Symfony Book和Cookbook,我想实现自己的安全访问检查,这可以吗?因为它缺少角色中的某些功能,例如具有类型"if is.author then canedit"

的约束

难以实施吗? FOS UserBundle有这个功能吗? (未在文档中显示)。

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以实施symfony2选民来定义访问权限:

http://symfony.com/doc/2.0/cookbook/security/voters.html

http://kriswallsmith.net/post/15994931191/symfony2-security-voters

让我们创建我们的选民类:

class PostAuthorVoter implements VoterInterface
{
    public function supportsAttribute($attribute)
    {
        return 'POST_AUTHOR' === $attribute;
    }

    public function supportsClass($class)
    {
        return $class instanceof Post;
    }

    public function vote(TokenInterface $token, $object, array $attributes)
    {
        // $attributes is an array so we do a foreach loop
        foreach ($attributes as $attribute)
        {
            // if $attribute is POST_AUTHOR and $object is an instance of Post
            if ($this->supportsAttribute($attribute) && $this->supportsClass($object))
            {
                $user = $token->getUser();

                // assuming that $posts in an \Doctrine\Common\Collections\ArrayCollection
                // we check that user's posts contains the current $object
                if ($user->getPosts()->contains($object))
                {
                    return VoterInterface::ACCESS_GRANTED;
                }
                else
                {
                    return VoterInterface::ACCESS_DENIED;
                }
            }
        }

        return VoterInterface::ACCESS_ABSTAIN;
    }
}

然后你就可以在控制器中调用安全组件的isGranted方法,如下所示:

if (!$this->get('security.context')->isGranted('POST_AUTHOR', $post)) {
    throw new AccessDeniedException();
}