Класс AbstractAuthenticator
Класс AbstractAuthenticator является абстрактным базовым классом для создания собственных аутентификаторов в Symfony. Он реализует интерфейс AuthenticatorInterface и предоставляет готовую структуру для обработки аутентификации через систему Passport. Класс содержит методы authenticate, onAuthenticationSuccess, onAuthenticationFailure и start, которые можно переопределять в зависимости от логики приложения.
Основное назначение класса - упростить создание кастомных аутентификаторов, избавляя разработчика от необходимости реализовывать все методы интерфейса вручную. Достаточно унаследоваться от AbstractAuthenticator и определить только те методы, которые действительно нужны.
Синтаксис
abstract class AbstractAuthenticator implements AuthenticatorInterface
{
abstract public function supports(Request $request): ?bool;
public function authenticate(Request $request): Passport;
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response;
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response;
public function start(Request $request, ?AuthenticationException $authException = null): Response;
}
Пример
Давайте создадим простой аутентификатор на основе класса AbstractAuthenticator, который проверяет наличие заголовка с токеном:
<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
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 ApiTokenAuthenticator extends AbstractAuthenticator
{
public function supports(Request $request): ?bool
{
return $request->headers->has('X-AUTH-TOKEN');
}
public function authenticate(Request $request): Passport
{
$apiToken = $request->headers->get('X-AUTH-TOKEN');
return new SelfValidatingPassport(
new UserBadge($apiToken)
);
}
public function onAuthenticationSuccess(Request $request, $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return new JsonResponse(['error' => 'Authentication failed'], Response::HTTP_UNAUTHORIZED);
}
}
?>
В данном примере метод supports проверяет наличие заголовка X-AUTH-TOKEN, метод authenticate создаёт паспорт с UserBadge, а метод onAuthenticationFailure возвращает JSON-ответ с ошибкой.
Пример
Давайте переопределим метод onAuthenticationSuccess для перенаправления пользователя после успешного входа:
<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
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 FormAuthenticator extends AbstractAuthenticator
{
public function supports(Request $request): ?bool
{
return $request->request->has('username');
}
public function authenticate(Request $request): Passport
{
$username = $request->request->get('username');
return new SelfValidatingPassport(
new UserBadge($username)
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return new RedirectResponse('/dashboard');
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return new Response('Authentication failed', Response::HTTP_UNAUTHORIZED);
}
}
?>
После успешной аутентификации пользователь будет перенаправлен на страницу /dashboard.
Смотрите также
-
класс
Passport,
который представляет собой объект с учётными данными пользователя -
класс
AbstractLoginFormAuthenticator,
который является расширением для аутентификации через форму входа -
класс
UserBadge,
который хранит идентификатор пользователя для загрузки -
класс
SelfValidatingPassport,
который используется для аутентификации без проверки пароля