11

I'm working over Symfony 2.0.16

I have in my UserProvider the method getRoles

public function getRoles()
{
    /**
     * @var \Doctrine\Common\Collections\ArrayCollection $rol
     */
    return $this->rol->toArray();
}

and my Rol entity has the role interface

class Rol implements \Symfony\Component\Security\Core\Role\RoleInterface
//...
public function getRole()
{
    return $this->getName();
}

but when I try to login I get the following error

Fatal error: Call to a member function getRole() on a non-object in C:\Users\julian\Code\parqueadero\vendor\symfony\src\Symfony\Bundle\SecurityBundle\DataCollector\SecurityDataCollector.php on line 57

Reading the class SecurityDataCollector, the error is thrown by a Closure

array_map(function ($role){ return $role->getRole();}, $token->getRoles()

Now I change this to

array_map(function ($role){ var_dump($role); return $role->getRole();}, $token->getRoles()

To my surprise, $role is a object Rol but I can't understand why I get the error.

1
  • array_map calls this function for all the elements returned by getTokens. Are you sure all of them are Rol objects? Commented Sep 3, 2012 at 17:34

3 Answers 3

14

I found the solution the problem is a bug in PHP 5.4 (the php i'm using) serialize method the github user yoannch proposed this solution, is overwrite the serialize/unserialize methods using json_encode/json_decode methods

class User implements \Serializable

//...

/**
 * Serializes the content of the current User object
 * @return string
 */
public function serialize()
{
    return \json_encode(
            array($this->username, $this->password, $this->salt,
                    $this->rol, $this->id));
}

/**
 * Unserializes the given string in the current User object
 * @param serialized
 */
public function unserialize($serialized)
{
    list($this->username, $this->password, $this->salt,
                    $this->rol, $this->id) = \json_decode(
            $serialized);
}

only need change the correct name properties

5
  • Thanks for saving me another day searching what the hell is wrong with my code. I'll just revert to 5.3.x. I've had tons of problems because of 5.4.
    – tftd
    Commented Dec 17, 2012 at 13:58
  • more info in the "official issue": github.com/symfony/symfony/issues/3691
    – unairoldan
    Commented Apr 22, 2013 at 20:33
  • Thks for the reference :) but as Ztere0 said, there's an official solution on Github Commented Jul 12, 2013 at 12:19
  • @YoannCh that was the solution i've found ^_^
    – rkmax
    Commented Jul 12, 2013 at 15:57
  • Your answer helped me a lot, but looks like roles are not being serialized do you know what can be wrong ?
    – PeterFour
    Commented Aug 17, 2015 at 11:36
11

I had the same problem (Windows, PHP 5.4.5), updated to 5.4.7 and it still did not work. Nevertheless, I came up with a workaround that needs less maintenance (when overwriting the serialization functions as described in the article you mentioned, you'll have to keep them up to date when adding/removing fields). So far it works for me, I hope there are no other problems resulting from the workaround I might have forgotten. Just alter the User's getRoles() function like that:

/**
 * @inheritDoc
 */
public function getRoles()
{
    $roles = array();
    foreach ($this->userRoles as $role) {
        $roles[] = $role->getRole();
    }

    return $roles;
}

Note that $role->getRole() returns the role name as a String (e.g. ROLE_ADMIN).

1
  • Cool workaround. I have tested it and it works! Thank you @MichaelB
    – stollr
    Commented Oct 10, 2012 at 6:38
6

solution of this problem is very simple. All problems associated with circular references at yours User and Role objects. So you have not to serialize User::$roles and Role::$users fields.

Look at Symfony\Component\Security\Core\Authentication\Token\AbstractToken::__construct() and Symfony\Component\Security\Core\Authentication\Token\AbstractToken::serialize().

How you can see, Symfony take your user's roles by invoking UserInterface::getRoles() before serialization. And serialize User and Roles separately.

You have to implement \Serializable interface in User and Role entities.

Example:

/**
 * Acme\Bundle\UserBundle\Entity\User
 * 
 * @ORM\Table(name="`user`")
 * @ORM\Entity(repositoryClass="Acme\Bundle\UserBundle\Entity\UserRepository")
 */
class User implements AdvancedUserInterface, EquatableInterface, \Serializable
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $username
     * 
     * @ORM\Column(type="string", length=30, unique=true)
     */
    private $username;

    /**
     * @var string $email
     * 
     * @ORM\Column(type="string", length=100, unique=true)
     */
    private $email;

    /**
     * @var string $salt
     *
     * @ORM\Column(type="string", length=40)
     */
    private $salt;

    /**
     * @var string $password
     *
     * @ORM\Column(type="string", length=128)
     */
    private $password;

    /**
     * @var boolean $isActive
     *
     * @ORM\Column(type="boolean")
     */
    private $isActive;

    /**
     * User's roles. (Owning Side)
     * 
     * @var ArrayCollection
     * 
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
     */
    private $roles;

    // .....

    /**
     * @see \Serializable::serialize()
     */
    public function serialize()
    {
        /*
         * ! Don't serialize $roles field !
         */
        return \serialize(array(
            $this->id,
            $this->username,
            $this->email,
            $this->salt,
            $this->password,
            $this->isActive
        ));
    }

    /**
     * @see \Serializable::unserialize()
     */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->email,
            $this->salt,
            $this->password,
            $this->isActive
        ) = \unserialize($serialized);
    }

}
/**
 * Acme\Bundle\UserBundle\Entity\Role
 *
 * @ORM\Table(name="role")
 * @ORM\Entity
 * 
 */
class Role implements RoleInterface, \Serializable
{
    /**
     * @var integer $id
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $role
     *
     * @ORM\Column(name="role", type="string", length=20, unique=true)
     */
    private $role;

    /**
     * Users in group (Inverse Side)
     * 
     * @var ArrayCollection
     * 
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
     */
    private $users;

    // .....    

    /**
     * @see \Serializable::serialize()
     */
    public function serialize()
    {
        /*
         * ! Don't serialize $users field !
         */
        return \serialize(array(
            $this->id,
            $this->role
        ));
    }

    /**
     * @see \Serializable::unserialize()
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->role
        ) = \unserialize($serialized);
    }
}

And all will be serialized/unserialized correctly.

See discus at https://github.com/symfony/symfony/issues/3691

See also: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/entities-in-session.html#serializing-entity-into-the-session

3
  • For some reason this is not working with me. Symfony2.1.3 & php 5.4.9. I get successfully login but then I get an exception in the logs [2012-12-17 17:19:26] security.INFO: Authentication exception occurred; redirecting to authentication entry point (A Token was not found in the SecurityContext.) [] [] and I'm pointed back to the login page.
    – tftd
    Commented Dec 17, 2012 at 14:33
  • Look for errors in your code. Or show me the code of security.yml and the user model. I'll try to help. Commented Dec 25, 2012 at 23:04
  • I believe that this solution is correct. See discus on the GitHub: github.com/symfony/symfony/issues/3691#issuecomment-9831914 Commented Mar 21, 2013 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.