-1

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

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

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

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

带有内联注释的控制器:

/**
 * @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 是如何工作的呢?什么时候应该使用拒绝访问功能?

4

1 回答 1

1

让我们尝试改变 POV。

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

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

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

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

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

安全.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
    }
}
于 2021-09-27T08:09:22.527 回答