简体   繁体   English

如何重定向在symfony中,如何在身份验证后重定向到身份验证之前的URL?

[英]How to redirect In symfony, how to redirect after authentication, on the URL before authentication?

I want a user to login (login page) and be redirected to the page on which they were before authentication. 我希望用户登录(登录页面)并重定向到他们在身份验证之前所在的页面。

For information, I created the login page using the make:auth -command and the redirection (in the code) is done in this code in the AppAuthenticator -class: 有关信息,我使用make:auth -command创建了登录页面,并且重定向(在代码中)是在AppAuthenticator -class的以下代码中完成的:

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    return new RedirectResponse($this->urlGenerator->generate('page_to_redirect'));
}

It looks like you are using a GuardAuthenticator. 您好像正在使用GuardAuthenticator。 In that case you can use the TargetPathTrait to get the target path from the session. 在这种情况下,您可以使用TargetPathTrait从会话获取目标路径。

use TargetPathTrait;

...

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    $targetPath = $this->getTargetPath($request->session, $providerKey);

    return new RedirectResponse($targetPath);
}

You might also want to provide a fallback, eg back to the homepage or read the info from another location, eg from an additional url query-parameter that you can set or you could also read it from the header, if you enable use_referer in your firewall . 如果您启用了use_referer ,那么您可能还希望提供一个后备功能,例如返回首页或从其他位置读取信息,例如从您可以设置的其他url查询参数中读取,也可以从标题中读取它防火墙

Since the target path is not a route name, you don't need to use the UrlGenerator to retrieve the path for that route name. 由于目标路径不是路由名称,因此不需要使用UrlGenerator来检索该路由名称的路径。

And thank you for your answer. 并感谢您的回答。 I tried your solution, but I got another problem. 我尝试了您的解决方案,但遇到了另一个问题。 In fact I found the solution: When I enter the controller (before login), I store the route to redirect in the session: 实际上,我找到了解决方案:当我进入控制器时(登录之前),我将重定向路径存储在会话中:

>     /**
>      * @Route("/blog", name="blog")
>      */
>     public function blog(Request $request)
>     {
>         $request->getSession()->set("referer","blog");
>         return $this->render('main/blog.html.twig', [
>             'controller_name' => 'MainController',
>         ]);
>     }

And in the AppAuthenticator.php, I get the data using the referer : 在AppAuthenticator.php中,我使用引荐来源获取数据:

 public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) { $url = $request->getSession()->get('referer'); return new RedirectResponse($this->urlGenerator->generate($url)); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM