Symfony 4 EasyAdmin how to encrypt passwords?

混江龙づ霸主 提交于 2019-12-20 01:46:32

问题


I am using EasyAdmin to add/edit users and wanted to ask if there is a possibility of encrypting your passwords? Password encryption worked previously when I used the Symfony 4 make:registration-form but I can't use that now, I have to use EasyAdmin.

easy_admin.yaml

easy_admin:
  entities:
    User:
     class: App\Entity\User
     password_encoding: { algorithm: 'bcrypt', cost: 12 }

(Actual) I go to EasyAdmin page (/admin), click User, Add User, fill in email (test@gmail.com) and password (test), click Save Changes.

Now the user is stored in the database but with plaintext password.

(Expected) All of the above but password is encrypted.


回答1:


Extend EasyAdmin controller and handle User entity. Something like this:

namespace AppBundle\Controller\Admin;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController as BaseAdminController;
use AppBundle\Entity\User;

class AdminController extends BaseAdminController
{
    protected function prePersistUserEntity(User $user)
    {
        $encodedPassword = $this->encodePassword($user, $user->getPassword());
        $user->setPassword($encodedPassword);
    }

    protected function preUpdateUserEntity(User $user)
    {
        if (!$user->getPlainPassword()) {
            return;
        }
        $encodedPassword = $this->encodePassword($user, $user->getPlainPassword());
        $user->setPassword($encodedPassword);
    }

    private function encodePassword($user, $password)
    {
        $passwordEncoderFactory = $this->get('security.encoder_factory');
        $encoder = $passwordEncoderFactory->getEncoder($user);
        return $encoder->encodePassword($password, $user->getSalt());
    }

}



来源:https://stackoverflow.com/questions/54744836/symfony-4-easyadmin-how-to-encrypt-passwords

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!