【问题标题】:Symfony: How to get the current User Role in a Formtype or security.authorization_checkerSymfony:如何在表单类型或 security.authorization 检查器中获取当前用户角色
【发布时间】:2024-05-20 08:30:02
【问题描述】:

我有一个表单类型,我需要访问当前的用户角色,因为我想决定显示哪些字段。 例如,是否可以访问security.authorization_checker,以便我可以创建一个 if 子句:

if (!$this->get('security.authorization_checker')->isGranted('IS_ADMIN')) { ....

【问题讨论】:

  • 您可以将该 FormType 作为服务然后注入容器,您可以像上面那样做。

标签: symfony security authentication symfony-2.3 symfony-3.1


【解决方案1】:

如上所述,您可以根据我使用的这段代码创建您的 onw 表单,以便在任何非管理员用户处呈现字段:

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Validator\Constraints\IsTrue as TrueConstraint;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;

class RegistrationType extends AbstractType
{

    /**
    * @var AuthorizationChecker
    */
    private $authorizationChecker=null;

    public function __construct(AuthorizationChecker $authorizationChecker)
    {
      $this->authorizationChecker=$authorizationChecker;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name',TextType::class,["label"=>"register.name","required"=>true,'translation_domain' => 'FOSUserBundle'])
                ->add('surname',TextType::class,["label"=>"register.surname","required"=>true,'translation_domain' => 'FOSUserBundle']);

        if(!$this->authorizationChecker->isGranted('ROLE_ADMIN'))
        {
          $builder->add('accept_terms',CheckboxType::class,["label"=>"register.acceptTerms","required"=>true,'translation_domain' => 'FOSUserBundle',
                                                            'mapped' => false,'constraints' => new TrueConstraint(array('message' => 'Your Confirmation Message','groups' => 'Registration'))]);
        }
    }

   // Extra stuff ommited for convenience
}

如您所见,如果用户是管理员,我会通过 $this->authorizationChecker->isGranted('ROLE_ADMIN') 一段代码使用。

所以您只需将'@security.authorization_checker' 作为服务参数。

【讨论】:

    【解决方案2】:

    您可以将表单注册为服务,然后将security.authorization_checker 作为参数传递,请查看以下示例代码。

    form.service.id:
        class: YourFormClass
        arguments: ['@security.authorization_checker']
        tags:
            - { name: form.type }
    

    然后在您的表单类中创建__construct(AuthorizationChecker $authorizationChecker) 方法,然后使用AuthorizationChecker 来检查ROLE

    【讨论】:

    • 不,在 Symfony 3 中不允许在 fromtype 中有构造函数
    • 不,我使用的是 symfony 3.2,它允许我在表单中添加 __construct(),您在哪里发现 symfony3* 不允许在 formType 中使用 __construct?事件你可以在 symfony3.2 文档中找到 __construct,检查symfony.com/doc/current/form/use_empty_data.html
    • @MaulikSavaliya 完全同意你的观点,我们可以在任何版本的 symfony 形式中使用构造方法。
    • AuthorizationChecker的命名空间是什么?
    • Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
    最近更新 更多