如何将用户密码迁移到 Symfony FOSUserBundle table

How to migrate users passwords to Symfony FOSUserBundle table

我有一个旧网站,我想将其迁移到 Symfony2 并使用 FOSUserBundle。

我的 'old' 网站的数据库存储加密密码如下:

sha1(\"$salt1$plain_text_password$salt2\")

但是,我以前没有这样做过,也不确定如何去做。我唯一的选择是以某种方式配置 FOSUserBundle 以使用与旧网站相同的加密吗?如果是这样,我应该在哪里做?

您可以创建自定义密码编码器并覆盖BasePasswordEncoder ::isPasswordValid()在其中添加您的逻辑

例子

class CustomPasswordEncoder extends BasePasswordEncoder
{
   public function encodePassword($raw,$salt){
       list($salt1,$salt2) = explode(",",$salt);
       return sha1($salt1.$raw.$salt2); // your logic here
   }
    public function isPasswordValid($encoded,$raw,$salt)
    {
      return $this->comparePasswords(
       $encoded,$this>encodePassword($raw,$salt));
    }
}

使此 class 成为一项服务

service.yml
services:
    custom-password-encoder:
        class: path\to\CustomPasswordEncoder

并将其添加到您的 security.yml

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: {id: custom-password-encoder}

您还需要将 User::getSalt() 更改为 return 以逗号分隔的两种盐

例子

Class User extends BaseUser
{
    public function getSalt()
    {
        return "salt1,salt2";
    }
}

Magento 迁移密码逻辑的片段。

<?php

namespace AppBundle\Utils;

use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;

class CustomPasswordEncoder extends BasePasswordEncoder
{
    public function encodePassword($raw, $salt)
    {
        $salt2 = base64_encode($salt.uniqid());

        // logic from magento
        return md5($salt2.$raw).":".$salt2;
    }

    public function isPasswordValid($encoded, $raw, $salt)
    {
        // magento logic
        $hashArr = explode(':', $encoded);
        $hashToValidate = md5($hashArr[1] . $raw);

        return $this->comparePasswords(
           $hashArr[0], // first piece of password
           $hashToValidate // $salt.$password md5 hash
        );
    }
}