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