Symfony 3 - не может применяться роли пользователя - PullRequest
1 голос
/ 06 мая 2019

У меня есть объект UserCas, который реализует UserInterface.

Мои пользователи играют роль:

enter image description here

Однако, когда я ограничиваю доступ к некоторым страницам на основе ролей, это не работает.

Итак, в контроллере я проверил моего пользователя, у которого есть ROLE_ADMIN:

$user = $this->getUser();

        if($this->container->get('security.authorization_checker')->isGranted('ROLE_ADMIN'))
        {
            dump("yes");
        }

        else
        {
            dump("no");
        }

И дамп вернул "нет".

Если я дам дамп $ user-getRoles (), я получу:

enter image description here

Итак, в чем проблема, пожалуйста?

Моя сущность UserCas:

<?php

namespace Site\PagesBundle\Entity;

use Serializable;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Site\PagesBundle\Security\Traits\traitUser;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Site\PagesBundle\Entity\PaquetDDLCas;

/**
 * UserCas
 *
 * @ORM\Table(name="user_cas")
 * @ORM\Entity(repositoryClass="Site\PagesBundle\Repository\UserCasRepository")
 * @UniqueEntity("mail")
 */
class UserCas implements \Serializable, UserInterface
{

    use traitUser;
    // Some attributes and methods


    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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


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


    /************ MODIF ****************/

    /**
     * @ORM\Column(type="array")
     */
    protected $roles = [];

     /**
     * {@inheritdoc}
     */
    public function addRole($role)
    {
        $role = strtoupper($role);
        if ($role === ['ROLE_USER']) {
            return $this;
        }

        if (!in_array($role, $this->roles, true)) {
            $this->roles[] = $role;
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     * @return array
     */
    public function getRoles()
    {
        return array_unique(array_merge(['ROLE_USER'], $this->roles));
    }

    /**
     * {@inheritdoc}
     */
    public function hasRole($role)
    {
        return in_array(strtoupper($role), $this->getRoles(), true);
    }

    /**
     * {@inheritdoc}
     */
    public function removeRole($role)
    {
        if (false !== $key = array_search(strtoupper($role), $this->roles, true)) {
            unset($this->roles[$key]);
            $this->roles = array_values($this->roles);
        }

        return $this;
    }

        /**
     * {@inheritdoc}
     */
    public function setRoles(array $roles)
    {
        $this->roles = array();

        foreach ($roles as $role) {
            $this->addRole($role);
        }

        return $this;
    }

    public function resetRoles()
    {
        $this->roles = [];
    }

    /******************* FIN MODIF  *********************/



    /**
     * Constructor
     */
    public function __construct()
    {
        $this->setEnabled(true);
        $this->roles = array();

    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }


    /**
     * @return string
     */
    public function getMail()
    {
        return $this->mail;
    }

    public function setMail($mail)
    {
        $this->mail = $mail;
    }

    /**
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }


    public function serialize()
    {
        return serialize([
            $this->id,
            $this->username,
            $this->mail
        ]);
    }

    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->username,
            $this->mail
        ) = unserialize($serialized);
    }



    /*********************** Méthodes pour UserInterface ***************************/

    public function eraseCredentials()
    {
    }

    /**
     * {@inheritdoc}
     */
    public function getSalt()
    {

    }

    /**
     * {@inheritdoc}
     */
    public function getPassword()
    {

    }


}

1 Ответ

5 голосов
/ 06 мая 2019

Вы можете установить ограничение на security.yml

- { path: ^/admin/*, roles: [ROLE_ADMIN] }
...