3

我最近开始为我的 Symfony2 项目设置安全性。我选择使用盐使用 sha256 进行编码。当我尝试使用数据库中的示例帐户(使用自计算的 sha256 salt/hash)登录时,它一直失败而没有给我任何错误消息,我不知道为什么。我决定在我的控制器的 loginAction() 方法中加入一些简单的代码。当用户使用指定的表单登录失败时,这是 Symfony2 调用的方法。我输入了以下代码:

$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);

但是,当我尝试登录时,Symfony2 给了我以下错误:

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

所以基本上,它的意思是 的参数getEncoder()必须是 的一个实例Symfony\Component\Security\Core\User\UserInterface。但是,当我检查 MyProject\MyBundle\Entity\Users.php 时,它以以下几行开头:

<?php
namespace MyProject\MyBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;

...

所以Users类实际上实现了UserInterface类。它包含 UserInterface 类中的所有功能。我按照 Symfony2 教程告诉我的方式创建了所有这些文件。Symfony2 无法将我的 Users 实例识别为 UserInterface 实例的原因是什么?

PS:数据库是别人创建的,我只需要使用它。Users 表包含的信息比 UserInterface 所需的信息多得多。

4

1 回答 1

14

没关系,我是个白痴。

我忘记了,除了包含 UserInterface 类之外,您还必须确保您的类实现了 UserInterface。

我把它改成这样:

class Users implements UserInterface

它现在完美运行。

于 2012-03-04T09:36:46.307 回答