You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony中如何在Expression与PHP属性中为is_granted传递Subject

Symfony 6.2 中使用IsGranted属性实现多条件权限校验的问题

我正在基于Symfony 6.2、Doctrine 2和PHP 8开发项目,希望通过IsGranted(PHP属性)对控制器方法进行权限校验,具体需同时满足以下三个条件:

  • is_granted('ROLE_OPERATOR_USER') AND
  • is_granted(OperatorVoter::UPDATE) AND
  • is_granted(OperatorRightVoter:HAS_RIGHT, $operator)

为实现多条件的AND逻辑,我使用了Expression,但无法将参数$operator作为subject传入Expression中的is_granted方法。

我的代码

控制器方法代码

#[Route(path        : '/edit/{id}',
        name        : 'resources_operator_edit',
        requirements: ['id' => '\d+'],
        options     : ['menu' => true],
        defaults    : ['user_activity' => ['access' => true, 'name' => 'platform_user_activity.operator_edit']],
        methods     : ['GET', 'POST'])
]
#[IsGranted(
    attribute: new Expression("is_granted('ROLE_GA_OPERATOR_USER') and is_granted(constant('\\\App\\\Security\\\Voter\\\OperatorVoter::UPDATE'))
and is_granted(constant('\\\App\\\Security\\\Voter\\\OperatorRightVoter::HAS_RIGHT'), operator)"),
    subject  : new Expression('args["operator"]')
)]
public function edit (Request $request, Operator $operator): Response
{
// some code
}

OperatorRightVoter代码

class OperatorRightVoter extends Voter
{
    const HAS_RIGHT = 'operatorHAS_RIGHT';

    public function __construct (protected RequestStack $requestStack, protected Security $security)
    {
    }

    protected function supports ($attribute, $subject): bool
    {
        if ($attribute != self::HAS_RIGHT) {
            return false;
        }

        return true;
    }

    /**
     * @inheritDoc
     */
    protected function voteOnAttribute (string $attribute, $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();

        // the user must be logged in; if not, deny permission
        if (!$user instanceof User) {
            return false;
        }

        dd($subject);
        dd($user->getBusinessUnit()->hasPermissionOperator($subject));
//        if ($this->security->isGranted('ROLE_GA_OPERATOR_ADMIN')) {
//            return true;
//        }
     }
}

问题核心

我尝试设置subject并传入属性,但Expression内的is_granted无法识别operator变量,仅内置变量如user可正常使用。我希望通过PHP属性实现校验,而非在方法内调用->isGranted(),请问该如何解决?

内容的提问来源于stack exchange,提问作者Rady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:59:59