Класс PasswordAuthenticatedUserInterface
Интерфейс PasswordAuthenticatedUserInterface
реализуется классом пользователя, чтобы система
аутентификации Symfony могла получать хеш пароля.
Он требует единственный метод getPassword,
который возвращает хешированный пароль пользователя,
хранящийся в базе данных. Обычно этот интерфейс
применяется вместе с UserInterface.
Синтаксис
interface PasswordAuthenticatedUserInterface
{
public function getPassword(): ?string;
}
Пример
Давайте создадим класс пользователя, реализующий
интерфейс PasswordAuthenticatedUserInterface:
<?php
namespace AppEntity;
use DoctrineORMMapping as ORM;
use SymfonyComponentSecurityCoreUserPasswordAuthenticatedUserInterface;
use SymfonyComponentSecurityCoreUserUserInterface;
#[ORMEntity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn(type: 'integer')]
private ?int $id = null;
#[ORMColumn(type: 'string', length: 180, unique: true)]
private string $email = '';
#[ORMColumn(type: 'string')]
private string $password = '';
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getUserIdentifier(): string
{
return $this->email;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getRoles(): array
{
return ['ROLE_USER'];
}
public function eraseCredentials(): void
{
}
}
?>
Пример
Давайте проверим, что объект пользователя возвращает корректный пароль:
<?php
use AppEntityUser;
$user = new User();
$user->setEmail('user@example.com');
$user->setPassword('$2y$13$abcdefghijklmnopqrstuv');
$res = $user->getPassword();
echo $res;
?>
Результат выполнения кода:
"$2y$13$abcdefghijklmnopqrstuv"
Пример
Давайте используем интерфейс в проверке
подлинности пользователя через UserPasswordHasher:
<?php
namespace AppController;
use AppEntityUser;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentPasswordHasherUserPasswordHasherInterface;
use SymfonyComponentSecurityCoreUserPasswordAuthenticatedUserInterface;
class SecurityController extends AbstractController
{
public function check(
UserPasswordHasherInterface $hasher,
PasswordAuthenticatedUserInterface $user
): Response {
$res = $hasher->isPasswordValid($user, 'abcde');
return new Response($res ? 'valid' : 'invalid');
}
}
?>
Результат выполнения кода при верном пароле:
valid
Смотрите также
-
интерфейс
UserInterface,
который реализует любой класс пользователя -
метод
getPassword,
который возвращает хеш пароля пользователя -
класс
UserPasswordHasher,
который хеширует и проверяет пароли -
метод
isPasswordValid,
который проверяет соответствие пароля хешу