How to redirect to different url based on roles in symfony 2

后端 未结 6 1160
梦谈多话
梦谈多话 2020-12-02 17:37

I have one login page on site. I have 4 different tye of users and i want that when they login they go to different page based on their role assigned.

Is there any w

6条回答
  •  暖寄归人
    2020-12-02 18:28

    One way to solve this is to use an event listener on the security.interactive_login event. In this case I simply attach another listener in that event listener so it will fire on the response. This lets the authentication still happen but still perform a redirect once complete.

    
        
        
        
        
    
    

    And the class...

    class SecurityListener
    {
        protected $router;
        protected $security;
        protected $dispatcher;
    
        public function __construct(Router $router, SecurityContext $security, EventDispatcher $dispatcher)
        {
            $this->router = $router;
            $this->security = $security;
            $this->dispatcher = $dispatcher;
        }
    
        public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
        {
            $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
        }
    
        public function onKernelResponse(FilterResponseEvent $event)
        {
            if ($this->security->isGranted('ROLE_TEAM')) {
                $response = new RedirectResponse($this->router->generate('team_homepage'));
            } elseif ($this->security->isGranted('ROLE_VENDOR')) {
                $response = new RedirectResponse($this->router->generate('vendor_homepage'));
            } else {
                $response = new RedirectResponse($this->router->generate('homepage'));
            }
    
            $event->setResponse($response);
        }
    }
    

提交回复
热议问题