user2879565 user2879565 - 2 years ago 192
PHP Question

Symfony redirect to login via controller

I'm in the middle of a Symfony 2.5 project.
My firewall is set to ask the autentication to every route that have /secured/ prefix.
I have different types of users ADMIN_ROLE , USER_ROLE and anonymous.
My need is to redirect each of them to a different page, if logged and to the login screen if anonymous if the try to enter on the path /web/app.php/

I've created the following route:

pattern: /
defaults: { _controller: MyHomeBundle:Default:redirect }

And i've created the folowing controller:

public function redirectAction(){
if ($this->get('security.context')->isGranted('ROLE_ADMIN')){
$render = $this->forward('MyHomeBundle:Installation:selectInstallation', array('userId'=>$user=$this->get('security.context')->getToken()->getUser()->getId()) );
$render = $this->forward('MyHomeBundle:Installation:selectInstallation', array('userId'=>$user=$this->get('security.context')->getToken()->getUser()->getId()) );
else {
return $render;

In the "else" of the function i shoud punt the redirect to the login screen if the user is not an admin and not an user, but the login is managed by the firwall of symfony defined in the security.yml and i have no route to that. How che redirect to the url .../login without having an explicit countroller loginAction?

Answer Source

In the security.yml you can specify a login_path, in example:

    pattern: ^/(secured_area)/
    provider: my_provider
    anonymous: ~
        login_path:  my_login_path
        default_target_path: /dashboard

And in the routing.yml you can map the route as:

    pattern:   /my/relative/url/for/login
    defaults:  { _controller: MySecurityBundle:Security:login }

then you can use an a normal route, in you specific case:

return $this->forward($this->generateUrl('my_login_path'));

Hope this help

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download