如何管理symfony中的角色

时间:2019-04-10 16:18:31

标签: symfony4 roles

我有一个注册表,允许管理员创建用户并为他分配明确定义的角色。 创建后,如果我尝试与我拥有的角色建立联系,该应用程序将向我显示资源访问错误

secyrity.yaml

security:
    encoders:
        App\Entity\User:
            algorithm: bcrypt
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory: { memory: ~ }
        in_database:
            entity:
                class: App\Entity\User
                property: name
    role_hierarchy:
        # Un admin hérite des droits d'utilisateur et de souscommission
        ROLE_ADMIN:       ROLE_SOUSCOMMISSION
        # On garde ce rôle superadmin, il nous resservira par la suite
        #ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true

            provider:
                in_database

            form_login:
                login_path: security_login
                check_path: security_login
            logout:
                path: security_logout
                target: home

            # activate different ways to authenticate

            # http_basic: true
            # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: true
            # https://symfony.com/doc/current/security/form_login_setup.html

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/admin/traitement, roles: ROLE_SOUSCOMMISSION }

我的婴儿推车上的动作 在我的控制器中,我定义了他的动作

 /**
     * @Route("/inscription", name="security")
    */
    public function inscription(Request $request, ObjectManager $manager, UserPasswordEncoderInterface $encoder)
    {
        $user= new User();
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $hash = $encoder->encodePassword($user, $user->getPassword());
            $user->setPassword($hash);
            $manager->persist($user);
            $manager->flush();

            return $this->redirectToRoute('security_login');
        }



        return $this->render('security/inscrie.html.twig', [

            'form' => $form->createView(),
        ]);
    }

     /**
     * @Route("/login", name="security_login")
    */
    public function login(AuthenticationUtils $authenticationUtils)
    {
        $error = $authenticationUtils->getLastAuthenticationError();
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', [ 

        'last_username'=>$lastUsername,

        'error' =>$error
    ]);
}

UserType.php

<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('name')
            ->add('password',  PasswordType::class)
            ->add('password_confirme', PasswordType::class)
            ->add('roles', ChoiceType::class, [
                'label' =>'Role',
                'placeholder'=>'',
                'multiple'=>true,
                'choices' =>[
                    'Administrateur'=>'ROLE_ADMIN',
                    'Traiteur ' =>'ROLE_SOUSCOMMISSION',
                ],
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

User.php

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\EqualTo;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\EqualTo(propertyPath= "password_confirme")
     */
    private $password;
    /**
     * @Assert\EqualTo(propertyPath= "password", message="Vous n'avez pas taper le meme mot de passe")
     */
    public $password_confirme;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $email;

    /**
     * @ORM\Column(type="array", nullable=true)
     */
    private $roles = [];



    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }


    public function getUserName(){}

    public function eraseCredentials(){}
    public function getSalt(){}

        public function getRoles(){
            return $this->roles;
        }

        public function setRoles(?array $roles): self
        {
            $this->roles = $roles;

            return $this;
        }




}

当我尝试与角色ROLE_SOUCOMMISSION连接时,我遇到了类型错误的访问被拒绝。  请帮忙!

2 个答案:

答案 0 :(得分:1)

这是因为/admin/traitement/admin下,因此无法转到此页面,因为您需要角色ROLE_ADMIN才能转到/admin。您需要反转它们或将/admin设置为ROLE_SOUSCOMMISSION角色

答案 1 :(得分:1)

只需更改security.yaml中访问控制的位置即可将具有用户权限的用户添加到具有ROLE_SOUSCOMMISSION的位置,因为

  

Symfony从列表的顶部开始,并在找到第一个匹配项时停止

文档:access_control

access_control:
    - { path: ^/admin/traitement, roles: ROLE_SOUSCOMMISSION }
    - { path: ^/admin, roles: ROLE_ADMIN }

谢谢