Symfony 类PasswordEncoderSubsciber实现EventSubscriberInterface

Symfony 类PasswordEncoderSubsciber实现EventSubscriberInterface,symfony,Symfony,当我通过Api platflorm的Post请求创建用户时,我希望在将传输的密码插入数据库之前对其进行哈希处理 目前,用户在bdd中创建得很好,但密码始终处于清除状态。因此,我的订户似乎被摧毁了。。。但是我不明白为什么或者如何调试 如果有人有线索,我很感兴趣 我的代码 <?php namespace App\Events; use ApiPlatform\Core\EventListener\EventPriorities; use App\Entity\User; use Symfo

当我通过Api platflorm的Post请求创建用户时,我希望在将传输的密码插入数据库之前对其进行哈希处理

目前,用户在bdd中创建得很好,但密码始终处于清除状态。因此,我的订户似乎被摧毁了。。。但是我不明白为什么或者如何调试

如果有人有线索,我很感兴趣

我的代码

<?php

namespace App\Events;

use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class PasswordEncoderSubsciber implements EventSubscriberInterface
{
    /**
     * @var UserPasswordEncoderInterface
     */
    private $encoder;

    public function __construct(UserPasswordEncoderInterface $encoder)
    {
        $this->encoder = $encoder;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['encodePassword', EventPriorities::PRE_WRITE],
        ];
    }

    public function encodePassword(ViewEvent $event): void
    {
        $user = $event->getControllerResult();
        dd($user);
        $method = $event->getRequest()->getMethod();
        if ($user instanceof User && 'POST' === $method) {
            $hash = $this->encoder->encodePassword($user, $user->getPassword());
            $user->setPassword($hash);
        }
    }
}

您的代码看起来不错,因此请确认您已在security.yaml中设置了编码器

security:
    encoders:
        # use your user class name here
        App\Entity\User:
            # bcrypt or argon2i are recommended
            # argon2i is more secure, but requires PHP 7.2 or the Sodium extension
            algorithm: argon2i
试试这个代码,它更干净:

public function encodePassword(ViewEvent $event)
{
    $user = $event->getControllerResult();
    $method = $event->getRequest()->getMethod();

    if (!$user instanceof User || Request::METHOD_POST !== $method) {
        return;
    }

    // encode password

    $user->setPassword(
        $this->passwordEncoder->encodePassword(
            $user,
            $user->getPassword()
        )
    );

}

我投票结束这个问题,因为这里的问题应该用英语写,而不是法语,对不起,我更改了语言当控制器操作不返回响应时发送视图事件。为什么您认为它是一个对密码进行哈希运算的合适位置?通常,您会使用与创建用户相同的代码对密码进行编码。您可以向我们显示用户实体和用于创建用户的url吗?我这里有哈希,因为我需要在将其添加到数据库之前使用预写将其添加