Monday, January 10, 2022

[FIXED] Symfony denyAccessUnlessGranted in Controller constructor

Issue

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?


Solution

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
}


Answered By - G1.3

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.