如何根据symfony 2中的角色重定向到不同的URL

时间:2012-07-16 14:11:48

标签: php symfony

我在网站上有一个登录页面。 我有4种不同类型的用户,我希望他们在登录时根据分配的角色转到不同的页面。

有什么办法吗?

6 个答案:

答案 0 :(得分:29)

解决此问题的一种方法是在security.interactive_login事件上使用事件侦听器。在这种情况下,我只是在该事件监听器中附加另一个监听器,因此它将触发响应。这样可以使身份验证仍然发生,但仍然可以在完成后执行重定向。

<service id="sotb_core.listener.login" class="SOTB\CoreBundle\EventListener\SecurityListener" scope="request">
    <tag name="kernel.event_listener" event="security.interactive_login" method="onSecurityInteractiveLogin"/>
    <argument type="service" id="router"/>
    <argument type="service" id="security.context"/>
    <argument type="service" id="event_dispatcher"/>
</service>

班级......

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);
    }
}

答案 1 :(得分:10)

对于Symfony&gt; = 2.6现在将是:

<?php

namespace CommonBundle\Listener;

use Monolog\Logger;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

class LoginListener
{
    /** @var Router */
    protected $router;

    /** @var TokenStorage */
    protected $token;

    /** @var EventDispatcherInterface */
    protected $dispatcher;

    /** @var Logger */
    protected $logger;

    /**
     * @param Router $router
     * @param TokenStorage $token
     * @param EventDispatcherInterface $dispatcher
     * @param Logger $logger
     */
    public function __construct(Router $router, TokenStorage $token, EventDispatcherInterface $dispatcher, Logger $logger)
    {
        $this->router       = $router;
        $this->token        = $token;
        $this->dispatcher   = $dispatcher;
        $this->logger       = $logger;
    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        $this->dispatcher->addListener(KernelEvents::RESPONSE, [$this, 'onKernelResponse']);
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        $roles = $this->token->getToken()->getRoles();

        $rolesTab = array_map(function($role){
            return $role->getRole();
        }, $roles);

        $this->logger->info(var_export($rolesTab, true));

        if (in_array('ROLE_ADMIN', $rolesTab) || in_array('ROLE_SUPER_ADMIN', $rolesTab)) {
            $route = $this->router->generate('backend_homepage');
        } elseif (in_array('ROLE_CLIENT', $rolesTab)) {
            $route = $this->router->generate('frontend_homepage');
        } else {
            $route = $this->router->generate('portal_homepage');
        }

        $event->getResponse()->headers->set('Location', $route);
    }
}

和services.yml

services:
common.listener.login:
    class: CommonBundle\Listener\LoginListener
    arguments: [@router, @security.token_storage, @event_dispatcher, @logger]
    scope: request
    tags:
        - { name: kernel.event_listener, event: security.interactive_login, method: onSecurityInteractiveLogin }

答案 2 :(得分:8)

  

在Symfony 3.1中测试

您还可以在用户成功登录security.yml文件中的所有用户后设置默认路径,如下所示:

<强> [配置/ 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: ~
...
default_target_path方法中的

然后会根据用户角色进行简单的重定向。很直接。有人说最简单的方法总是最好的方式。你决定:)

<强> [SomeBundle /控制器/ 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');
    }
}

像魅力一样工作,但请记住,如果您的ROLE_ADMIN还具有ROLE_USER等权限,请始终向下检查大多数受限制的角色......

答案 3 :(得分:4)

我使用了Mdrollette的答案,但这个解决方案有一个很大的缺点,你完全覆盖了symfony的原始响应,并通过这样做删除了由symfony在标题中设置的记住我的cookie。

我的解决方案是以这种方式更改OnKernelResponse:

public function onKernelResponse(FilterResponseEvent $event)
{
    if ($this->security->isGranted('ROLE_TEAM')) {
        $event->getResponse()->headers->set('Location', $this->router->generate('team_homepage'));    
    } elseif ($this->security->isGranted('ROLE_VENDOR')) {
        $event->getResponse()->headers->set('Location', $this->router->generate('vendor_homepage'));
    } else {
        $event->getResponse()->headers->set('Location', $this->router->generate('homepage'));
    }
}

这样你就可以完整地记住我。

答案 4 :(得分:2)

如果您正在寻找比@MDrollette更简单的答案,您可以将类似的重定向块放入登录成功页面的控制器中。

答案 5 :(得分:0)

为了测试,如果您想要保留原始响应,您也可以只复制标题。 Redirect对象上的clone方法仅复制标头。

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'));
    }

    $response->headers = $response->headers + $event->getResponse()->headers;

    $event->setResponse($response);
}