Symfony2 Error: UsernamePasswordToken::serialize() must return a string or NULL

Getting the following error? Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL
I was getting it while trying to login a user. The thing was, in my Role entity, all properties were private.
class Role implements RoleInterface
{
private $id;
private $name;
private $created_at;
// ...
}
When doing some googling and checking things out, I found this comment on php.net which gave me an idea. I changed all private properties to protected and thing worked!
class Role implements RoleInterface
{
protected $id;
protected $name;
protected $created_at;
// ...
}
thanks a lot.. you made me able to progress my work on the project with upgraded versions of symfony 🙂
Thank You, that helped me!
In my case, the problem was in one of my other entities, but related to User as well.
By the way, I’m wondering, why entities fields are generated with ‘private’ keyword if that problem exists..
I have got the same problem :/
but in my case it is because my User entity uses an relationship with Group. so the serialize crashes :/
how can I fix it ?
please, reply in my email. thx.
I think that making all properties in User aswell as in Group entity protected should do the trick.
Just don’t use the private access modifier.
You can also leave the properties private and add a serialization interface
class Role implements RoleInterface, \Serializable
{
//…
public function serialize()
{
return serialize(array(
$this->id,
$this->password,
$this->username
));
}
public function unserialize($serialized)
{
list(
$this->id,
$this->password,
$this->username
) = unserialize($serialized);
}
}
^of course the fields in serialize and unserialize should be according to the class attributes (id, name).
It’s worth to add that you need to serialize only the credentials used in authentication (like entity user: id, username, password).
Thank you very much !
It worked once more 🙂
[…] http://www.metod.si/symfony2-error-usernamepasswordtokenserialize-must-return-a-string-or-null/ Tagged: authenticationmappingquestionssymfony-2.0 /* * * CONFIGURATION VARIABLES: […]
I modified all my entities to protected and did the trick, thanks a lot!!!
Metod and @thorinkor thanks the tips.
Great! Replacing all ‘private’ in my User entity worked. Strangely enough it worked before…
Putting this in my user entity solved the problem:
public function __sleep()
{
return array('id');
}
thanks it worked greatlly .
Better to use this solution : http://asiermarques.com/2013/symfony2-security-usernamepasswordtokenserialize-must-return-a-string-or-null/. (define __sleep() function)