如何在Symfony 4中使用fos用户将用户迁移到新的密码哈希算法



我有一个带有fos用户的旧Symfony 2应用程序,其中包含用sha512算法编码的密码。

我希望在将表用户迁移到带有fos用户2.1的新应用程序symfony 4后,当用户使用侦听器登录时,能够使用算法bcrypt修改密码。

在Symfony下,有可能有几个编码器,但问题是我们不能用不同的算法复制相同的编码器,比如:

encoders:
FOSUserBundleModelUserInterface: sha512
FOSUserBundleModelUserInterface: bcrypt

或者有了这个代码,我收到了这个错误消息:

"security.encoders.old"下无法识别的选项"FOS\UserBundle\Model\UserInterface">

encoders:
old:
FOSUserBundleModelUserInterface:
algorithm: sha512
new:
FOSUserBundleModelUserInterface:
algorithm: bcrypt

本周早些时候发布的Symfony 4.4更新。

4.4支持密码迁移。

将您的编码器声明为"自动",因此Symfony将始终为新密码选择尽可能好的编码器,并为旧密码选择合适的编码器:

encoders:
FOSUserBundleModelUserInterface:
algorithm: auto
cost: 14

然后让您的UserRepository实现PasswordUpgraderInterface。该接口包括一个方法upgradePassword(),每当散列需要升级到更新的算法时,就会调用该方法。

文档中的示例实现如下:

// ...
use SymfonyComponentSecurityCoreUserPasswordUpgraderInterface;
class UserRepository extends EntityRepository implements PasswordUpgraderInterface
{
// ...
public function upgradePassword(UserInterface $user, string $newEncodedPassword): void
{
// this code is only an example; the exact code will depend on
// your own application needs
$user->setPassword($newEncodedPassword);
$this->getEntityManager()->flush($user);
}
}

根据您的用例进行调整,当用户登录到您的应用程序时,您将能够透明地将经过哈希处理的密码更新为最新的哈希算法。

由于现代哈希算法将哈希存储在与哈希密码相同的字段上,如果旧的哈希机制依赖于单独的哈希字段,则可以在此过程中将其设置为null,因为不再需要它。

这个新功能的好消息。所以我迁移到了4.4版本。

我用更改了Fos user的自定义用户提供商


use SymfonyComponentSecurityCoreUserPasswordUpgraderInterface;
public function upgradePassword(SecurityUserInterface $user, string $newEncodedPassword): void
{
// set the new encoded password on the User object
$user->setPassword($newEncodedPassword);
//you can set salt to null because the new encoders use algorithms without the salt
$user->setSalt(null);
// store the new password
$this->userManager->updateUser($user);
}

这很管用!

但Fos User捆绑包的一个问题是,当用户修改密码时,会创建一个新的salt,但它没有被使用。最重要的是它有效。

最新更新