Home > Software engineering >  Symfony denyAccessUnlessGranted in Controller constructor
Symfony denyAccessUnlessGranted in Controller constructor

Time:09-17

I have a controller with many actions:

class SomeController extends AbstractController
{

    public function indexAction()
    {
        $this->denyAccessUnlessGranted('ROLE_SUPERMANAGER');
        [...]
    }

    public function someAjaxAction()
    {
        $this->denyAccessUnlessGranted('ROLE_SUPERMANAGER');
        [...]
    }
    
    public function someOtherAjaxAction()
    {
        $this->denyAccessUnlessGranted('ROLE_SUPERMANAGER');
        [...]
    }
}

Why I can't just do this, to deny access in all the actions of that controller?

public function __construct()
{
    $this->denyAccessUnlessGranted('ROLE_SUPERMANAGER');
}

I got Call to a member function has() on null on AbstractController.php:218:

if (!$this->container->has('security.authorization_checker')) {

Is there any way to do that in the controller class, besides a rule in security.yaml?

CodePudding user response:

You can add the SensioFrameworkExtraBundle's isGranted annotation at class level like this:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

/**
 * @IsGranted("ROLE_SUPERMANAGER")
**/
class SomeController extends AbstractController
{
   // Your actions without auth check in each
}
  • Related