在Symfony 3.4中手动哈希(即编码)字符串值

问题描述 投票:0回答:1

Symfony 3.4中是否可以在没有实现UserInterface的实体的情况下使用密码编码器?


详细信息

我想在Symfony 3.4中对随机字符串值进行哈希处理。我总是可以使用password_hash,但是我正在尝试以Symfony的方式进行操作并利用框架。这就是我卡住的地方:

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

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

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

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个回答
0
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.