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

Today I got the following exception in a web application that uses Doctrine2 Entities and the Symfony Security Component with Silex framework (this can also appear in Symfony2 framework).

Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL

ErrorException: Notice: serialize(): "id" returned as member variable from __sleep() but does not exist in /../vendor/symfony/security/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php line 149

The error appears when you have a Doctrine Entity implementing the UserInterface with a relation mapped in it.

The solution is as simple as implement the __sleep() magic method in that entity in this way.


public function __sleep(){
   return array('id', 'username', 'email');
}

This sets the id, email and username as the desired attributes to serialize ignoring the mappings and other properties in the Entity.

3 comentarios en “Symfony2 Security UsernamePasswordToken::serialize() must return a string or NULL”

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *