Reputation: 610
I have recently started setting up the security for my Symfony2 project. I opted to encode with sha256 using a salt. When I tried to login with a sample account in the database (with self-calculated sha256 salt/hash), it kept failing without giving me any error messages and I could not figure out why. I decided to put some simple code in the loginAction() method of my Controller. This is the method that Symfony2 calls when a user fails to login using the specified form. I entered the following code:
$factory = $this->get('security.encoder_factory');
$em = $this->container->get('doctrine')->getEntityManager();
$userRep = $em->getRepository('MyProjectMyBundle:Users');
$user = $userRep->find(2);
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword('cookie', 'thisisasalt');
$user->setPassword($password);
print($password);
However, when I tried to login, Symfony2 gave me the following error:
Catchable Fatal Error: Argument 1 passed to Symfony\Component\Security\Core\Encoder\EncoderFactory::getEncoder() must be an instance of Symfony\Component\Security\Core\User\UserInterface, instance of MyProject\MyBundle\Entity\Users given, called in /var/www/Symfony/src/MyProject/MyBundle/Controller/MainController.php on line 35 and defined in /var/www/Symfony/vendor/symfony/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php line 33
So basically, it's saying that the argument of getEncoder()
must be an instance of Symfony\Component\Security\Core\User\UserInterface
. However, when I inspect MyProject\MyBundle\Entity\Users.php, it starts with the following lines:
<?php
namespace MyProject\MyBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
...
So the Users class actually implements the UserInterface class. It contains all the functions in UserInterface class. I have created all these files in the way the Symfony2 tutorial told me to. What is the reason Symfony2 doesn't recognize my Users instance as an UserInterface instance?
P.S.: The database was created by someone else, I just have to work with it. The Users table contains many more information than just that required by UserInterface.
Upvotes: 3
Views: 5614
Reputation: 610
Nevermind, I am an idiot.
I forgot that, in addition to including the UserInterface class, you also have to make sure your class implements the UserInterface.
I changed it to this:
class Users implements UserInterface
It now works perfectly.
Upvotes: 14