在symfony中没有用户实例的哈希用户密码 [英] Hash user password without User instance in symfony

查看:51
本文介绍了在symfony中没有用户实例的哈希用户密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在官方文档(当前程序)中进行阅读在Symfony框架中手动哈希密码的方法如下:

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);
}

encodePassword 方法要求将User实例作为其第一个参数传递.因此,在调用该方法时必须预先存在User实例:这意味着必须在没有有效哈希密码的情况下实例化"User".我希望改为将密码作为构造函数参数提供,以便User实体在创建时处于有效状态.

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.

是否有使用Symfony哈希密码的另一种方法?

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

推荐答案

UserPasswordEncoder使用所谓的EncoderFactory来确定给定类型的用户的确切密码编码器.将您的代码调整为:

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);

这应该可以正常工作.请注意,getEncoder可以采用类实例或类名称.

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

还请注意,需要为盐明确发送null.由于某些原因,某些Symfony编码器类还没有默认的salt值.

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.

这篇关于在symfony中没有用户实例的哈希用户密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆