FOSUserBundle - How to redirect already logged-in users when trying to access the login_path

前端 未结 5 2255
太阳男子
太阳男子 2020-12-19 14:02

Is it possible to perform an automatic redirect to the some route (i.e. /) for the specific route /login only for users that are AUTHENTICATED? and

5条回答
  •  北海茫月
    2020-12-19 14:46

    As you are using FOSUserBundle the rendering of the login form takes place in SecurityController::renderLogin().

    The solution is bascially:

    • overriding the SecurityController
    • adding a check for the role IS_AUTHENTICATD_ANONYMOUSLY
    • redirecting the user to another page if the role was not found

    I assume you have already created a bundle extending FOSUserBundle which holds your User Entity.

    I assume this bundle is called YourUserBundle and is located at src/Your/Bundle/UserBundle.

    Now copy (not cut) the SecurityController

    vendor/friendsofsymfony/user-bundle/src/FOS/UserBundle/Controller/SecurityController.php
    

    to (in order to override the one provided by FOSUserBundle)

    src/Your/Bundle/UserBundle/Controller/SecurityController.php
    

    add the use-statement for RedirectResponse and edit the renderLogin() method like this:

    use Symfony\Component\HttpFoundation\RedirectResponse;
    
    // ...
    
    protected function renderLogin(array $data)
    {
        if (false === $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
            return new RedirectResponse('/', 403);
        }
    
        $template = sprintf('FOSUserBundle:Security:login.html.%s', $this->container->getParameter('fos_user.template.engine'));
    
        return $this->container->get('templating')->renderResponse($template, $data);
    }
    

    Update

    Now instead of security.context use security.authorization_checker.

    http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

提交回复
热议问题