Я обновляю старое приложение для использования Symfony (v4) в качестве серверной части, и я застрял, пытаясь запустить аутентификацию. Моя база данных хранит хешированные пароли и соли для пользователя, пароли использовали функцию crypt php. Я также использую пакет lexik JWT, пытаясь вернуть токен во внешний интерфейс.
Я не могу получить ответ от symfony / lexik, кроме "плохие учетные данные".
Я считать, моя проблема коренится в части кодировщики, я попытался реализовать собственный кодировщик паролей, потому что crypt использует модифицированный алгоритм DES в соответствии с документами php, и простое использование следующего в моем security.yaml не работает.
encoders:
App\Entity\DB_1\User:
algorithm: DES
Вот мой полный security.yaml
security.yaml
security:
encoders:
App\Entity\DB_1\User:
id: 'App\Security\MyPasswordEncoder'
providers:
entity_provider:
entity:
class: App\Entity\MetallicBonds\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login
stateless: true
anonymous: true
json_login:
check_path: /login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
register:
pattern: ^/register
stateless: true
anonymous: true
api:
pattern: ^/test
stateless: true
anonymous: false
provider: entity_provider
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
access_control:
- { path: ^/login_check, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/test, roles: IS_AUTHENTICATED_FULLY }
и мой пользовательский кодировщик паролей MyPasswordEncoder.php
namespace App\Security;
use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
class MyPasswordEncoder extends BasePasswordEncoder implements
PasswordEncoderInterface
{
private $ignorePasswordCase;
public function __construct($ignorePasswordCase = false)
{
$this->ignorePasswordCase = $ignorePasswordCase;
}
public function encodePassword($raw, $salt)
{
// TODO: Implement encodePassword() method.
return crypt($raw,$salt);
}
public function isPasswordValid($encoded, $raw, $salt)
{
// TODO: Implement isPasswordValid() method.
if ($this->isPasswordTooLong($raw)) {
return false;
}
try {
$pass2 = $this->encodePassword($raw, $salt);
} catch (BadCredentialsException $e) {
return false;
}
if (!$this->ignorePasswordCase) {
return $this->comparePasswords($encoded, $pass2);
}
return $this->comparePasswords(strtolower($encoded), strtolower($pass2));
}
}
Я хотел бы использовать сохраненные в настоящее время пароли, по крайней мере, на данный момент, чтобы переход со старой системы на новую был для конечных пользователей плавным. У кого-нибудь был успех с использованием пользовательского кодировщика паролей с Symfony 4?
Я должен отметить, что когда я помещаю точку останова xdebug в MyPasswordEncoder.php, она никогда не останавливает приложение, есть ли где-нибудь еще класс, который нужно зарегистрировать для Symfony, чтобы использовать его?
Виден ли отступ файла security.yaml в StackOverflow? Ключи encoders, providers и firewalls должны быть дочерними по отношению к ключу security, что, похоже, здесь не так.
Отступы правильные, просто неправильно скопировали и вставили в текстовое поле здесь






это мой security.yaml
security:
encoders:
App\Entity\User:
id: 'App\Security\Encoder\MyCustomPasswordEncoder'
это мой код
namespace App\Security\Encoder;
use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;
class MyCustomPasswordEncoder extends BasePasswordEncoder
{
private $algorithm;
private $encodeHashAsBase64;
private $iterations;
/**
* @param string $algorithm The digest algorithm to use
* @param bool $encodeHashAsBase64 Whether to base64 encode the password hash
* @param int $iterations The number of iterations to use to stretch the password hash
*/
public function __construct(string $algorithm = 'sha1', bool $encodeHashAsBase64 = false, int $iterations = 0)
{
$this->algorithm = $algorithm;
$this->encodeHashAsBase64 = $encodeHashAsBase64;
$this->iterations = $iterations;
}
/**
* {@inheritdoc}
*/
public function encodePassword($raw, $salt)
{
if ($this->isPasswordTooLong($raw)) {
throw new BadCredentialsException('Invalid password.');
}
if (!in_array($this->algorithm, hash_algos(), true)) {
throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm));
}
//$salted = $this->mergePasswordAndSalt($raw, $salt);
$salted = $salt.$raw;
$digest = hash($this->algorithm, $salted, true);
// "stretch" hash
for ($i = 1; $i < $this->iterations; ++$i) {
$digest = hash($this->algorithm, $digest.$salted, true);
}
return $this->encodeHashAsBase64 ? base64_encode($digest) : bin2hex($digest);
}
/**
* {@inheritdoc}
*/
public function isPasswordValid($encoded, $raw, $salt)
{
return !$this->isPasswordTooLong($raw) && $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));
}
}
Код запущен правильно. старый код - symfony 1.4.
Я сделал нечто подобное, вызывается ctor моего пользовательского класса, но не функция isPasswordValid. Вы знаете, почему? Я пытаюсь войти в систему с помощью пакета JWT.
Строго предположение, но я думаю, что вашему брандмауэру для входа в систему нужна запись поставщика.