douyiavxxh02727 2015-07-29 15:58
浏览 22
已采纳

在Symfony2中以编程方式登录自定义实体用户后,“Authenticated No”

Programmatically logging in the user through:

$user = new CustomEntityUser();
$user->setUsername("foo");
$user->setPassword("bar");

$entityManager->persist($user);
$entityManager->flush();

$token = new UsernamePasswordToken($user, $user->getPassword(), "main", $user->getRoles());
$this->get('security.token_storage')->setToken($token);

doesn't authenticate the user properly. The debug bar goes yellow and says: "Authenticated No". The name of the firewall is main.

The user-entity-class has implemented the Serializeable-interface according to documentation.

  • 写回答

1条回答 默认 最新

  • doushou9028 2015-07-29 15:58
    关注

    The solution was to have the user-entity-class implement the Symfony\Component\Security\Core\User\EquatableInterface, such as e.g.:

    /**
     * {@inheritdoc}
     */
    public function isEqualTo(UserInterface $user)
    {
        if (! $user instanceof User) {
            return false;
        }
    
        if ($this->username !== $user->getUsername()) {
            return false;
        }
    
        if ($this->password !== $user->getPassword()) {
            return false;
        }
    
        return true;
    }
    

    After doing this, the user is successfully authenticated.

    If above fix doesn't work, ensure that the data is properly validated. E.g:

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=40, unique=true)
     */
    private $username;
    

    and then generating a username with more than 40 characters will still give the same problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C