Hash user password without User instance in symfony

好久不见. 提交于 2021-02-02 09:28:08

问题


As it can be read in the official documentation, the current procedure to manually hash a password in the Symfony framework, is the following:

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

public function register(UserPasswordEncoderInterface $encoder)
{
    // whatever *your* User object is
    $user = new App\Entity\User();
    $plainPassword = 'ryanpass';
    $encoded = $encoder->encodePassword($user, $plainPassword);

    $user->setPassword($encoded);
}

The encodePassword method requires an User instance to be passed as its first argument. The User instance must therefore pre-exist when the method is called: this means that a 'User' must be instantiated without a valid hashed password. I'd like the password to be provided as a constructor argument instead, so that an User entity is in a valid state when it is created.

Is there an alternative way of hashing the password using Symfony?


回答1:


The UserPasswordEncoder uses what is known as an EncoderFactory to determine the exact password encoder for a given type of user. Adjust your code to:

public function register(EncoderFactoryInterface $encoderFactory)
{
    $passwordEncoder = $encoderFactory->getEncoder(User::class);
    $hashedPassword = $passwordEncoder->encodePassword($plainPassword,null);

And that should work as desired. Notice that getEncoder can take either a class instance or a class name.

Also note the need to explicitly send null for the salt. For some reason, some of the Symfony encoder classes do not have default values for salt yet.



来源:https://stackoverflow.com/questions/62980930/hash-user-password-without-user-instance-in-symfony

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