Метод getTargetPath
Метод getTargetPath принадлежит трейту TargetPathTrait
и возвращает путь, который был сохранён ранее
с помощью метода saveTargetPath. Первым
параметром передаётся объект RequestStack,
вторым - имя firewall. Если для указанного
firewall путь не был сохранён, метод вернёт
null.
Синтаксис
public function getTargetPath(RequestStack $requestStack, string $firewallName): ?string
Пример
Давайте сохраним целевой путь и затем получим его обратно:
<?php
namespace AppService;
use SymfonyComponentHttpFoundationRequestStack;
use SymfonyComponentSecurityHttpUtilTargetPathTrait;
class TargetPathService
{
use TargetPathTrait;
public function __construct(
private RequestStack $requestStack
) {
}
public function handle(): ?string
{
$this->saveTargetPath($this->requestStack, 'main', '/article');
$res = $this->getTargetPath($this->requestStack, 'main');
return $res;
}
}
?>
Результат выполнения кода:
"/article"
Пример
Давайте попробуем получить путь для firewall, для которого ничего не сохранялось:
<?php
namespace AppService;
use SymfonyComponentHttpFoundationRequestStack;
use SymfonyComponentSecurityHttpUtilTargetPathTrait;
class TargetPathService
{
use TargetPathTrait;
public function __construct(
private RequestStack $requestStack
) {
}
public function handle(): ?string
{
$res = $this->getTargetPath($this->requestStack, 'unknown');
return $res;
}
}
?>
Результат выполнения кода:
null
Пример
Давайте используем метод в authenticator, чтобы после успешного входа перенаправить пользователя на сохранённый адрес:
<?php
namespace AppSecurity;
use AppSecurityUser;
use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRequestStack;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityHttpAuthenticatorAbstractAuthenticator;
use SymfonyComponentSecurityHttpAuthenticatorPassport;
use SymfonyComponentSecurityHttpAuthenticatorPassportBadgeUserBadge;
use SymfonyComponentSecurityHttpSecurity;
use SymfonyComponentSecurityHttpUtilTargetPathTrait;
class AppAuthenticator extends AbstractAuthenticator
{
use TargetPathTrait;
public function __construct(
private RequestStack $requestStack
) {
}
public function supports(Request $request): ?bool
{
return $request->isMethod('POST') && $request->getPathInfo() === '/login';
}
public function authenticate(Request $request): Passport
{
$username = $request->request->get('_username', '');
return new Passport(
new UserBadge($username),
$request->request->get('_password', '')
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
$targetPath = $this->getTargetPath($this->requestStack, $firewallName);
if ($targetPath) {
return new RedirectResponse($targetPath);
}
return new RedirectResponse('/');
}
}
?>
Результат выполнения кода после входа
пользователя с сохранённым путём /article:
Redirect to /article
Смотрите также
-
трейт
TargetPathTrait,
который хранит целевой путь в сессии -
метод
saveTargetPath,
который сохраняет целевой путь -
метод
removeTargetPath,
который удаляет сохранённый путь -
класс
AbstractAuthenticator,
который используется для создания аутентификатора