问题
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