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

查看:19
本文介绍了在 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 SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;

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

    $user->setPassword($encoded);
}

encodePassword 方法需要一个 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.

还要注意需要为 salt 显式发送 null.出于某种原因,一些 Symfony 编码器类还没有盐的默认值.

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天全站免登陆