Symfony denyAccessUnlessGranted在控制器构造函数中

ryevplcw  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(145)

我有一个控制器,有许多动作:

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');
        [...]
    }
}

为什么我不能这样做,拒绝访问控制器的所有操作?

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

我在AbstractController上得到了Call to a member function has() on null。php:218:

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

除了security.yaml中的规则之外,在控制器类中还有什么方法可以做到这一点吗?

cbjzeqam

cbjzeqam1#

您可以在类级别添加SensioFrameworkExtraBundle的isGranted注解,如下所示:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

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

krugob8w2#

FrameworkExtraBundle已经被Symfony弃用,不鼓励使用它。可以对Symfony\Component\Security\Http\Attribute\IsGranted做同样的事情。这是一篇很好的文章,帮助了我https://nebkam.medium.com/symfony-deprecated-route-and-method-annotations-4d5e1d34556a

相关问题