如何根据 symfony 2 中的角色重定向到不同的 url [英] How to redirect to different url based on roles in symfony 2

查看:28
本文介绍了如何根据 symfony 2 中的角色重定向到不同的 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有什么办法吗?

推荐答案

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

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.

<service id="sotb_core.listener.login" class="SOTBCoreBundleEventListenerSecurityListener" 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);
    }
}

这篇关于如何根据 symfony 2 中的角色重定向到不同的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆