Search code examples
symfonyauthenticationsymfony-3.4

Trying to redirect user after login in Symfony using targetPath but it is always null


I've seen that $this->getTargetPath($request->getSession(), $providerKey) can be used to get the target path but it is always null.

Can someone explain what it is meant to do and why it is always null for me?

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);
        }
}

Solution

  • The only time target path is set from Symfony is when the user start the authentication flow, passing through the authentication entry point. This is done by the ExceptionListener. If you are using the FormAuthenticationEntryPoint, this happens when you try to access a restricted page, and you are (usually) redirected to the login page. At that point target path is set.

    Usually there's no reason to set it yourself, but you could do so by using TargetPathTrait's saveTargetPath like so:

    $this->saveTargetPath($request->getSession(), $providerKey, $request->getUri());