Home > Mobile >  When should I use the deny access functions in Symfony 4.4 controllers?
When should I use the deny access functions in Symfony 4.4 controllers?

Time:09-27

I was wondering how the security works in Symfony. I have in security.yaml this line of code:

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

This deny's access to everyone except users with admin roles going to /account-management and anything after.

Now I have a account management controller. But I am wondering if I ever need to use a deny access function like $this->denyAccessUnlessGranted('ROLE_ADMIN'); or $this->isGranted('ROLE_ADMIN').

Controller with inline comments:

/**
 * @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...
    }
}

So how does the security.yaml work? And when should the deny access functions be used?

CodePudding user response:

Let's try to change the POV.

Think about a system where more types of users are involved, e.g. Admins, Backoffice Operators (boh must be authenticated), and simple users that can access the frontend as anonymous or as authenticated for private content.

You could define a zone (let's call this "authenticated") where both Admins and BO-Operators can access but they have different responsabilities.

Simple Users Can visit the site, register, login to access their personal data, edit profile etc.

BOO They can add content, approve user registration etc.

Admins All the BOO stuffs plus delete Simple Users registration

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
    }
}
  • Related