2012-03-03 51 views
2

我最近开始为我的Symfony2项目设置安全性。我选择使用盐编码sha256。当我试图用数据库中的示例帐户登录(使用自我计算的sha256 salt/hash)时,它一直没有给我提供任何错误消息,我无法弄清楚为什么。 我决定在Controller的loginAction()方法中加入一些简单的代码。这是Symfony2在用户无法使用指定表单登录时调用的方法。我输入以下代码:Symfony2安全编码器无法识别UserInterface实例

$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 \实体\ Users.php,它开始采用下面几行:

<?php 
namespace MyProject\MyBundle\Entity; 

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

... 

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

P.S .:数据库是由其他人创建的,我只需要使用它。用户表包含的信息不仅仅是UserInterface所需的信息。

回答

6

没关系,我是个白痴。

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

我改成了这样:

class Users implements UserInterface 

现在的作品完美。

+1

我不认为你是个白痴。我不想在点击+1按钮时感到粗鲁:) - 这个消息来自一个没有实现'UserInterface'的白痴 – 2017-06-07 15:24:37

相关问题