РЕПЕТИТОР математика физика информатика
Для школьников и студентов. Подтягивание пробелов. ЦЭ, ЦТ, ОГЭ, ЕГЭ.
Идет набор на ЛЕТО. Жмите для подробностей:)
613 of 1361 menu

Класс PasswordUpgradeBadge

Класс PasswordUpgradeBadge используется в системе аутентификации Symfony. Он добавляется в паспорт Passport и сигнализирует системе, что пароль пользователя был проверен успешно, но его хеш устарел и требует пересчёта. Первым параметром передаётся исходный пароль в открытом виде, вторым - объект пользователя PasswordAuthenticatedUserInterface.

Бейдж позволяет автоматически обновлять хеш пароля после успешного входа, если в базе данных хранится устаревший алгоритм хеширования.

Синтаксис

new PasswordUpgradeBadge(string $plaintextPassword, PasswordAuthenticatedUserInterface $user)

Пример

Давайте добавим бейдж обновления пароля в аутентификаторе после успешной проверки учётных данных:

<?php namespace App\Security; use App\Entity\User; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials; class AppAuthenticator extends AbstractAuthenticator { public function supports(Request $request): ?bool { return $request->getPathInfo() === '/login'; } public function authenticate(Request $request): Passport { $password = $request->request->get('password', ''); $user = $request->request->get('user', ''); $userBadge = new UserBadge($user); $credentials = new PasswordCredentials($password); $passport = new SelfValidatingPassport($userBadge, [$credentials]); $userEntity = new User(); $passport->addBadge(new PasswordUpgradeBadge($password, $userEntity)); return $passport; } public function onAuthenticationSuccess(Request $request, $token, string $firewallName): ?Response { return null; } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { return null; } } ?>

Результат выполнения кода при успешной аутентификации:

"password hash upgraded"

Пример

Давайте проверим, как система обрабатывает бейдж через метод getBadge паспорта:

<?php namespace App\Security; use App\Entity\User; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; class AppAuthenticator extends AbstractAuthenticator { public function supports(Request $request): ?bool { return true; } public function authenticate(Request $request): Passport { $password = 'abcde'; $user = new User(); $passport = new SelfValidatingPassport(new UserBadge('user')); $passport->addBadge(new PasswordUpgradeBadge($password, $user)); $badge = $passport->getBadge(PasswordUpgradeBadge::class); if ($badge !== null) { echo 'Password upgrade badge found'; } return $passport; } } ?>

Результат выполнения кода:

"Password upgrade badge found"

Смотрите также

  • класс Passport,
    который представляет паспорт аутентификации
  • метод addBadge,
    который добавляет бейдж в паспорт
  • класс PasswordCredentials,
    который хранит учётные данные пароля
  • класс UserBadge,
    который идентифицирует пользователя
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить