尝试使用 targetPath 登录 Symfony 后重定向用户,但它始终为 null

Sar*_*oma 2 authentication symfony symfony-3.4

我已经看到$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);
        }
}
Run Code Online (Sandbox Code Playgroud)

Fed*_*kun 5

Symfony 设置的唯一时间target path是用户启动身份验证流程并通过身份验证入口点时。这是由ExceptionListener完成的。如果您使用的是FormAuthenticationEntryPoint,当您尝试访问受限页面时就会发生这种情况,并且您(通常)会被重定向到登录页面。此时target path已定。

通常没有理由自己设置它,但您可以通过使用 TargetPathTrait 的 saveTargetPath 来完成此操作,如下所示:

$this->saveTargetPath($request->getSession(), $providerKey, $request->getUri());
Run Code Online (Sandbox Code Playgroud)