我最近开始为我的 Symfony2 项目设置安全性。我选择使用盐用 sha256 进行编码。当我尝试使用数据库中的示例帐户(使用自行计算的 sha256 salt/hash)登录时,它一直失败而没有给我任何错误消息,我无法弄清楚原因。
我决定在我的 Controller 的 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 实例的原因是什么?

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

最佳答案

没关系,我是个白痴。

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

我把它改成这样:

class Users implements UserInterface

它现在可以完美运行。

关于security - Symfony 安全编码器无法识别用户界面实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9548700/

10-11 03:36