php - Symfony2 - 更改现有用户的编码器

标签 php symfony authentication passwords password-hash

如果您有包含用户及其密码的现有代码库,如何更改密码编码器并更新用户密码?

换句话说,假设所有用户密码均采用 MD5 格式,并且您希望转换为 PBKDF2。常见的策略是在用户下次登录时简单地重新哈希密码。

但是,我不确定如何在 Symfony 中执行此操作。它会在登录 Controller 中完成吗?或者有没有办法在 EncoderInterface 对象中做到这一点?

最佳答案

看看这个博客...似乎这就是您正在寻找的...

How to change the way Symfony2 encodes passwords

您需要扩展 MessageDigestPasswordEncoder 类,覆盖其方法并将该类复制到 bundle 中的 Security 文件夹(如果不存在,则创建一个) 查看以下如何扩展 MessageDigestPasswordEncoder 的示例

use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder as      BaseMessageDigestPasswordEncoder;

class MessageDigestPasswordEncoder extends BaseMessageDigestPasswordEncoder
{
    private $algorithm;
    private $encodeHashAsBase64;

    public function __construct($algorithm = 'sha512', $encodeHashAsBase64 = true, $iterations = 5000)
    {
        $this->algorithm = $algorithm;
        $this->encodeHashAsBase64 = $encodeHashAsBase64;
        $this->iterations = $iterations;
    }

    protected function mergePasswordAndSalt($password, $salt)
    {
        if (empty($salt)) {
            return $password;
        }

        return $salt.$password; // or do whatever you need with the password and salt
    }

    public function encodePassword($raw, $salt)
    {
        // this is the original code from the extended class, change it as needed

        if (!in_array($this->algorithm, hash_algos(), true)) {
            throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm));
        }

        $salted = $this->mergePasswordAndSalt($raw, $salt);
        $digest = hash($this->algorithm, $salted, true);

        // "stretch" hash
        for ($i = 1; $i < $this->iterations; $i++) {
            $digest = hash($this->algorithm, $digest.$salted, true);
        }

        return $this->encodeHashAsBase64 ? base64_encode($digest) :  bin2hex($digest);
    }
}

准备好类(class)后,更新 config.yml

# app/config/config.yml
# ...

parameters:
    security.encoder.digest.class: Ens\TestBundle\Security\MessageDigestPasswordEncoder

关于php - Symfony2 - 更改现有用户的编码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25754751/

相关文章:

php - MySQL LOAD DATA INFILE 存储行号

php - Symfony 5 如何在具有多对多关系的更新中自动发送当前用户

symfony - 覆盖路由器并将参数添加到特定路由(在使用路径/url 之前)

javascript - Bazinga Expose Translation Bundle 不翻译

php - 无法通过 PHP 连接到 MSSQL

authentication - 新站点有望支持哪些知名 OpenID 提供商?

php - 关闭 FPM 日志中的换行符

php - 使用 MySQL 创建触发器

php - mysql order by rand() 性能问题及解决方案

php - HTML 按钮 : Redirect on click