Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

symfony - How does symfony2 redirect to requested page after login

Say my route /booking/(.*) is protected by a firewall configuration in security.yml and it requires "ROLE_USER", when user tries to access any route that is preceded by "/booking/" the app redirects the user to login page for authentication.

So my question is, after user provides his credentials and gets authenticated, how is Symfony 2 able to redirect the user back to the page/route the user had requested for OR where does Symfony 2 store that route does it store it in some session or some where else.

Can we access it and how?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is possible and you can access the referring link (that is used if use_referer is set to true) in the session.

For instance, if you have a success_handler service on your form_login (in your firewall configuration) that redirects users based on some criteria (commonly roles) but you wanted to redirect the user to the referrer link if it was set you could access the referrer link like so:

$key = '_security.main.target_path'; #where "main" is your firewall name

//check if the referrer session key has been set 
if ($this->container->get('session')->has($key)) {
    //set the url based on the link they were trying to access before being authenticated
    $url = $this->container->get('session')->get($key);

    //remove the session key
    $this->container->get('session')->remove($key);
}
//if the referrer key was never set, redirect to a default route
else{
    $url = $this->router->generate('member_home');
}

return new RedirectResponse($url); 

Using the header to get the referrer (ie $request->headers->get('referer')) will not work in this case because it will always return the login link.

Thanks to Roman Marintsenko & Ryan Weaver for this blog


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...