【问题标题】:Symfony denyAccessUnlessGranted in Controller constructor控制器构造函数中的 Symfony denyAccessUnlessGranted
【发布时间】:2021-09-03 13:11:56
【问题描述】:

我有一个有很多动作的控制器:

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.php:218 上获得了Call to a member function has() on null

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

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

【问题讨论】:

  • 看看 AbstractController 的源代码。关于为什么你不能在控制器的构造函数中做事的答案将是显而易见的。几乎每个 Symfony 开发人员都必须经历这个成人礼。您可以使用 security.yaml 中的访问控制部分或控制器事件侦听器来完成同样的事情。
  • 我想了解“为什么你不能在控制器的构造函数中做事的答案”。在查看 AbstractController 的源代码后,对我来说一点也不明显。

标签: symfony symfony5


【解决方案1】:

您可以像这样在类级别添加 SensioFrameworkExtraBundle 的 isGranted annotation

use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

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

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    相关资源
    最近更新 更多