symfony 5 新的基于身份验证器的安全性 - createHasher() 必须是数组类型,给定的对象

symfony 5 new Authenticator-based Security - createHasher() must be of the type array, object given

我尝试使用自定义散列器将我的 symfony 旧应用程序迁移到最新的身份验证系统。

我面临以下问题

Argument 1 passed to Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory::createHasher() must be of the type array, object given, called in /var/apache/www/celian_sf/vendor/symfony/password-hasher/Hasher/PasswordHasherFactory.php on line 112

提交表单登录和返回护照对象时验证方法时出现错误

执行 bin/console security:hash-password 抛出完全相同的错误

对散列器配置使用标准算法auto错误消失但我进入了无限循环太多重定向

为了验证编码密码,我需要获取用户实例以检索总是不同的盐。

我知道 SHA1 不够强大,这不是遗留应用程序的重点

为什么会出现这个错误?我的实施有什么问题?

当前工作:

return new Passport(
      new UserBadge($login),
      new PasswordCredentials(
        
        function ($credentials, UserInterface $user) {
          return sha1($credentials . '||' . $user->getSalt()) === $user->getPassword();
        },
        $passw
      )
    );

我想将密码散列到我的自定义散列器中。

security.yaml

security:
    enable_authenticator_manager: true

    providers:
        # nom du provider
        myprovider:
            # type de provider
            entity:
                class: App\Entity\Utilisateur
                property: loginUtil

    password_hashers:
        App\Entity\Utilisateur:
            id: App\Security\ShaOneEncoder
    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            anonymous: false
            provider: myprovider
         
            user_checker: App\Security\UserChecker
        
            access_denied_handler: App\Security\AccessDeniedHandler
            
            custom_authenticators:
                - App\Security\LoginFormAuthenticator
            logout:
                path: logout

LoginFormAuthenticator.php

<?php

namespace App\Security;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;

class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{

  private $params;

  public function __construct(ParameterBagInterface $params)
  {
    $this->params = $params;
  }

  /**
   * supports() - is called on every request
   *
   * @param Request $request
   * @return bool
   */
  public function supports(Request $request): bool
  {
    if (
        ($request->attributes->get('_route') === 'login_' . $request->getLocale()
          && $request->isMethod('POST'))
    ) {
        return true;
    }
  
    return false;
  }

  public function authenticate(Request $request): PassportInterface
  {
    // By default credentials are those of visiteur's account
    $login = $this->params->get('standard.login_visiteur');
    $passw = $this->params->get('standard.passwd_visiteur');

    // If user submitted form, get credentials from user's inputs
    if ($request->attributes->get('_route') === 'login_' . $request->getLocale() && $request->isMethod('POST')) {
      $login = $request->request->get('login');
      $passw = $request->request->get('passw');
    }

    return new Passport(new UserBadge($login), new PasswordCredentials($passw));
  }

  /**
   * Perform operations when authentication is success
   *
   * @param Request $request
   * @param TokenInterface $token
   * @param string $providerKey le nom du firewall derriere lequel l'utilisateur est authentifie
   * @return void
   */
  public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
  {
    // success
  }

  /**
   * Perform operations when authentication is failure
   *
   * @param Request $request
   * @param AuthenticationException $exception
   * @return void
   */
  public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
  {
    // failure
  }

  protected function getLoginUrl(Request $request): string
  {
    // TODO: Implement getLoginUrl() method.
    return $this->urlGenerator->generate('login_fr');
  }
}

ShaOneEncoder.php

<?php

namespace App\Security;

use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class ShaOneEncoder implements UserPasswordHasherInterface
{
    private $params;

    private $em;
    
    public function __construct(EntityManagerInterface $em, ParameterBagInterface $params)
    {
      error_log(__METHOD__);
      $this->params = $params;
      $this->em = $em;
    }
    /**
     * Encodes the raw password.
     *
     * @param string      $raw  The password to encode
     * @param string|null $salt The salt
     *
     * @return string The encoded password
     *
     * @throws BadCredentialsException   If the raw password is invalid, e.g. excessively long
     * @throws \InvalidArgumentException If the salt is invalid
     */
    public function encodePassword($raw, $salt)
    {
      error_log(__METHOD__);
        return sha1($this->mergePasswordAndSalt($raw, $salt));
    }
    /**
     * Checks a raw password against an encoded password.
     *
     * @param string      $encoded An encoded password
     * @param string      $raw     A raw password
     * @param string|null $salt    The salt
     *
     * @return bool true if the password is valid, false otherwise
     *
     * @throws \InvalidArgumentException If the salt is invalid
     */
    public function isPasswordValid(UserInterface $user, $raw)
    {
      error_log(__METHOD__);
        $encodedCredentials = $this->encodePassword($raw, $salt);

        if ($encodedCredentials === $encoded) {
            return true;
        }

        return false;

    }

    /**
     * Merges a password and a salt.
     *
     * @param string $password the password to be used
     * @param string $salt     the salt to be used
     *
     * @return string a merged password and salt
     *
     * @throws \InvalidArgumentException
     */
    protected function mergePasswordAndSalt($password, $salt)
    {
      error_log(__METHOD__);
        $passwd_separator = $this->params->get('standard.passwd_separator');
        
        return $password . $passwd_separator . $salt;
    }

    public function needsRehash(UserInterface $user): bool
    {
      error_log(__METHOD__);
        return true;
    }

    /**
     * Hashes a plain password.
     *
     * @throws InvalidPasswordException When the plain password is invalid, e.g. excessively long
     */
    public function hash(string $plainPassword): string
    {
      // should get the user to retrieve his salt then
      // return $this->encodePassword($plainPassword, $salt)
      die(__METHOD__);
    }

    /**
     * Verifies a plain password against a hash.
     */
    public function verify(string $hashedPassword, string $plainPassword): bool
    {
      die(__METHOD__); // Not executed except when using PasswordHasherInterface
      return $hashedPassword === $this->hash($plainPassword);
    }
}

如果我使用 PasswordHasherInterface 脚本执行验证方法但在使用 UserPasswordHasherInterface

时不执行

感谢@Cerad 解决方案是使用 Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface

Provides password hashing and verification capabilities for "legacy" hashers that require external salts.

https://github.com/symfony/symfony/blob/5.3/src/Symfony/Component/PasswordHasher/LegacyPasswordHasherInterface.php