【问题标题】:When should I use the deny access functions in Symfony 4.4 controllers?我什么时候应该在 Symfony 4.4 控制器中使用拒绝访问功能?
【发布时间】:2021-11-19 08:41:15
【问题描述】:

我想知道 Symfony 中的安全性是如何工作的。我在security.yaml这行代码:

# Admins can go to /account-management
- { path: '^/account-managent', roles: [ROLE_ADMIN] }

这拒绝对所有人的访问,除了具有管理员角色的用户进入 /account-management 和之后的任何内容。

现在我有一个帐户管理控制器。但我想知道我是否需要使用像 $this->denyAccessUnlessGranted('ROLE_ADMIN');$this->isGranted('ROLE_ADMIN') 这样的拒绝访问功能。

带有内联 cmets 的控制器:

/**
 * @Route("/account-management") // Is this class completely protected by security.yaml? Or does it work function specific?
 */
class AccountManagementController extends AbstractController
{
    /**
     * @Route("/{id}", name="account_management_delete", methods={"POST"})
     */
    public function deleteUser()
    {
        // I should not need this here right? Since I already have this configured in my security.yaml.
        // $this->denyAccessUnlessGranted('ROLE_ADMIN');

        # code...
    }

    public function handleUserData()
    {
        // Do I need this here? Since there is no route thing connected with this?
        $this->denyAccessUnlessGranted('ROLE_ADMIN');

        # code...
    }
}

那么 security.yaml 是如何工作的呢?什么时候应该使用拒绝访问功能?

【问题讨论】:

    标签: php symfony security controller symfony-4.4


    【解决方案1】:

    让我们尝试改变 POV。

    考虑一个涉及更多类型用户的系统,例如管理员、后台操作员(必须经过身份验证)以及可以匿名访问前端或针对私有内容进行身份验证的简单用户。

    您可以定义一个区域(我们称之为“已验证”),管理员和 BO 操作员都可以访问该区域,但他们有不同的职责。

    简单用户 可以访问网站、注册、登录以访问他们的个人数据、编辑个人资料等。

    他们可以添加内容、批准用户注册等。

    管理员 所有 BOO 东西加上删除简单用户注册

    security.yaml

    # Read https://symfony.com/doc/current/security.html#hierarchical-roles
    role_hierarchy:
        ROLE_ADMIN: ROLE_BACKOFFICE
    
    access_control:
        - { path: '^/authenticated', roles: [ROLE_BACKOFFICE] }
    
    /**
     * @Route("/authenticated") // It's protected by the firewall defined in security.yaml
     */
    class AccountManagementController extends AbstractController
    {
        /**
         * @Route("/{id}", name="account_management_delete", methods={"POST"})
         */
        public function deleteUser()
        {
            // As backoffice operators due to role hierarchy can access you should restrict the permissions to Admins
            $this->denyAccessUnlessGranted('ROLE_ADMIN');
    
            # code...
        }
    
        public function handleUserData()
        {
            // No control except the firewall needed as BOO can already access
        }
    }
    

    【讨论】:

    • 啊,我明白了,它和我想象的差不多。所以整个班级只能由 BOO 和管理员访问。并且只能由管理员删除用户。并且 handleUserData() 接管了该类的默认保护(BOO + 管理员)。感谢您的信息!
    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多