【问题标题】:Manually hash (i.e. encode) a string value in Symfony 3.4在 Symfony 3.4 中手动散列(即编码)字符串值
【发布时间】:2020-04-28 23:15:00
【问题描述】:

在 Symfony 3.4 中有没有一种方法可以在没有实现 UserInterface 的实体的情况下使用密码编码器?


详情

我想在 Symfony 3.4 中散列一个随机字符串值。我总是可以使用password_hash,但我正在尝试以 Symfony 的方式来做到这一点并利用框架。这就是我卡住的地方:

Symfony Documentation 有一个示例,但它使用了UserPasswordEncoder,它假定您有一个实现UserInterface 的实体作为第一个参数传递给encodePassword($user, $plainPassword)

在这种情况下,我没有用户实体,因为我正在为电子邮件链接生成令牌。我确实有一个实体,但是当它不是用户时让它实现UserInterface 感觉不对。

我研究了UserPasswordEncoder 的代码,并认为我可以注入具有通用encodePassword($plainPassword, $salt) 方法的PasswordEncoderInterface,但是当我尝试自动装配它时出现此异常:

Cannot autowire service "SriBundle\Service\PubMatch\PublicationMatchLogService":
argument "$passwordEncoder" of method "__construct()" references interface
"Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface" but no such service exists.
It cannot be auto-registered because it is from a different root namespace.

似乎 Symfony 没有实现 PasswordEncoder 并且可以自动装配的默认服务。我在这里遗漏了什么,或者 Symfony 是否假设您只想对用户实体的密码进行哈希处理,并且不支持在不传入关联用户的情况下为随机字符串值编码哈希?

【问题讨论】:

    标签: php symfony symfony-3.4 password-hash


    【解决方案1】:

    Symfony 中默认没有定义 PasswordEncoderInterface 实现服务。它们在内部与 UserPasswordEncoderInterface 一起使用。

    感谢 debug:container 命令,我发现了这一点。

    但是您可以自己轻松定义它们! 这是在 config/services.yaml 文件中使用 SodiumPasswordEncoder 的示例:

    services:
    
        # ... Your other definitions
    
        # Define an alias to allow autowiring on the interface
        Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface: '@password_encoder.sodium'
    
        # Define the concrete service
        # You can add the arguments entry if needed
        password_encoder.sodium:
            class: Symfony\Component\Security\Core\Encoder\SodiumPasswordEncoder
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 2016-05-20
      • 2015-05-31
      • 2023-04-06
      相关资源
      最近更新 更多