使用 targetPath 在 Symfony 中登录后尝试重定向用户,但它始终为 null
Trying to redirect user after login in Symfony using targetPath but it is always null
我看到 $this->getTargetPath($request->getSession(), $providerKey)
可以用来获取目标路径,但它总是 null
。
谁能解释一下它的用途以及为什么对我来说总是 null
?
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
use TargetPathTrait;
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$targetPath = $this->getTargetPath($request->getSession(), $providerKey);
if (!$targetPath) {
$targetPath = $this->container->get('router')
->generate('poll_index');
}
return new RedirectResponse($targetPath);
}
}
从 Symfony 设置的唯一一次 target path
是当用户启动身份验证流程时,通过身份验证入口点。这是由 ExceptionListener 完成的。如果您使用 FormAuthenticationEntryPoint
,当您尝试访问受限页面时会发生这种情况,并且您(通常)会被重定向到登录页面。此时 target path
已设置。
通常没有必要自己设置它,但您可以像这样使用 TargetPathTrait 的 saveTargetPath 来设置它:
$this->saveTargetPath($request->getSession(), $providerKey, $request->getUri());
我看到 $this->getTargetPath($request->getSession(), $providerKey)
可以用来获取目标路径,但它总是 null
。
谁能解释一下它的用途以及为什么对我来说总是 null
?
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
use TargetPathTrait;
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$targetPath = $this->getTargetPath($request->getSession(), $providerKey);
if (!$targetPath) {
$targetPath = $this->container->get('router')
->generate('poll_index');
}
return new RedirectResponse($targetPath);
}
}
从 Symfony 设置的唯一一次 target path
是当用户启动身份验证流程时,通过身份验证入口点。这是由 ExceptionListener 完成的。如果您使用 FormAuthenticationEntryPoint
,当您尝试访问受限页面时会发生这种情况,并且您(通常)会被重定向到登录页面。此时 target path
已设置。
通常没有必要自己设置它,但您可以像这样使用 TargetPathTrait 的 saveTargetPath 来设置它:
$this->saveTargetPath($request->getSession(), $providerKey, $request->getUri());