Symfony中如何在Expression与PHP属性中为is_granted传递Subject
Symfony 6.2 中使用IsGranted属性实现多条件权限校验的问题
我正在基于Symfony 6.2、Doctrine 2和PHP 8开发项目,希望通过IsGranted(PHP属性)对控制器方法进行权限校验,具体需同时满足以下三个条件:
is_granted('ROLE_OPERATOR_USER')ANDis_granted(OperatorVoter::UPDATE)ANDis_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
相关产品推荐
相关产品推荐

