Symfony 问题编辑用户时,如何存储正确编码的密码?
我没有使用FOSUserBundle,我自己创建了实体用户、角色等。配置如下所示:Symfony 问题编辑用户时,如何存储正确编码的密码?,symfony,Symfony,我没有使用FOSUserBundle,我自己创建了实体用户、角色等。配置如下所示: security: encoders: Bundle\UserBundle\Entity\User: algorithm: sha512 encode-as-base64: true iterations: 10 在创建时,我会这样做: if ($form->isValid()) {
security:
encoders:
Bundle\UserBundle\Entity\User:
algorithm: sha512
encode-as-base64: true
iterations: 10
在创建时,我会这样做:
if ($form->isValid()) {
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($entity);
$entity->setSalt(md5(time()));
$entity->setCompany($company);
$encoded_password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
$entity->setPassword($encoded_password);
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('user'));
}
但是,编辑任何用户时,密码显示为:
2cp/D6OTBEx4m2Y9xM/ku6rOtgODhrXK7//3Pd8D0jnZkOuusPB120Jwb6x+kan/52qSQuQxcUYDP1T6q6zqbw==
但是,如果我保存任何其他更改,密码会被覆盖,我无法再访问,同样,如果我输入一个新密码,它不会被编码(显然,因为我没有在updateAction上执行任何操作),但我想知道实现这一点的正确方法是什么
使用预更新?在“编辑”中分隔密码字段,以便该字段不会被覆盖 尝试使用设置密码。如果在用户编辑表单中遗漏了它们,则原则不会在DB中更新它们,也不会被覆盖
- 也不要使用
密码验证程序notBlank
$oldPass = $entity->getPassword(); // Handle form from request if ($form->isValid()) { if ($entity->getPassword() == '' || $entity->getPassword() == NULL) { $entity->setPassword($oldPass); } else { $factory = $this->get('security.encoder_factory'); $encoder = $factory->getEncoder($entity); $entity->setSalt(md5(time())); $entity->setCompany($company); $encoded_password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt()); $entity->setPassword($encoded_password); } $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('user')); }
plainPassword
),然后在prePersist/preUpdate侦听器中,如果plainPassword不为null,则编码并更新实际密码字段。