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

后端 未结 6 1183
梦谈多话
梦谈多话 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:36

    Tested in Symfony 3.1

    You could also set default path after user login successfully for all users in security.yml file like so:

    [config/security.yml]

    ...
    
    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern: /.*
            form_login:
                login_path: /login
                check_path: /login_check
                default_target_path: /login/redirect <<<<<<<<<<<<<<<<<<<<<<<<<
            logout:
                path: /logout
                target: /
            security: true
            anonymous: ~
    ...
    

    and then in default_target_path method make simple redirection based on user role. Very straight forward. Some say that the easiest way is always the best way. You decide :)

    [SomeBundle/Controller/SomeController.php]

    /**
     * Redirect users after login based on the granted ROLE
     * @Route("/login/redirect", name="_login_redirect")
     */
    public function loginRedirectAction(Request $request)
    {
    
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY'))
        {
            return $this->redirectToRoute('_login');
            // throw $this->createAccessDeniedException();
        }
    
        if($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN'))
        {
            return $this->redirectToRoute('_admin_panel');
        }
        else if($this->get('security.authorization_checker')->isGranted('ROLE_USER'))
        {
            return $this->redirectToRoute('_user_panel');
        }
        else
        {
            return $this->redirectToRoute('_login');
        }
    }
    

    Works like a charm but keep in mind to always check for most restricted roles downwards in case your ROLE_ADMIN also has privileges of ROLE_USER and so on...

提交回复
热议问题