大家好。我正在新的 Symfony 6.1 上做一个小项目。我连接了设备,因此有必要对密码进行哈希处理。翻遍码头,发现 PasswordHasherInterface
<?php
namespace App\DataFixtures;
use App\Model\User\Entity\User\Email;
use App\Model\User\Entity\User\Id;
use App\Model\User\Entity\User\Role;
use App\Model\User\Entity\User\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
class UserFixture extends Fixture
{
private PasswordHasherInterface $hasher;
public function __construct(PasswordHasherInterface $hasher)
{
$this->hasher = $hasher;
}
public function load(ObjectManager $manager): void
{
$hash = $this->hasher->hash("password");
$user = User::signUpByEmail(
Id::next(),
new \DateTimeImmutable(),
new Email("admin@app.test"),
$hash,
"token"
);
$user->confirmSignUp();
$user->changeRole(Role::admin());
$manager->persist($user);
$manager->flush();
}
}
但我收到一个错误:
In DefinitionErrorExceptionPass.php line 54:
!!
!! Cannot autowire service "App\DataFixtures\UserFixture": argument "$hasher"
!! of method "__construct()" references interface "Symfony\Component\PasswordH
!! asher\PasswordHasherInterface" but no such service exists. Did you create a
!! class that implements this interface?
!!
我的 services.yaml 文件:
parameters:
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Model/User/Entity/'
- '../src/Kernel.php'
如何在 Symfony 6.1 中散列密码?
该接口
PasswordHasherInterface
已由多个哈希器实现。自动装配将无法选择正确的。您必须在 services.yml 中手动指定或者为整个应用程序配置一个哈希器(https://symfony.com/doc/current/security/passwords.html#configuring-a-password-hasher)并通过将注入您的服务的工厂获取它