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

标签 php symfony

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

有什么办法吗?

最佳答案

解决此问题的一种方法是在 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)...

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

关于php - 如何根据 symfony 2 中的角色重定向到不同的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11506155/

相关文章:

php - 如何将这 3 个查询合并为一个 MySQL 查询?

不带引号的 PHP 数组访问

php - Mysql - 找不到特定记录的默认记录

php - property_path Symfony 表单选项中方括号的含义是什么

symfony - 无法在 Symfony 4 服务上注入(inject)模板

php - 为时间序列数据MySQL创建小时组

php - 如何从 .JS 文件中重置一次性 PHP 表单 token 以防止表单泛滥?

mysql - Doctrine 2 DQL CASE WHEN in Count

javascript - 如何使函数返回通过 AJAX 检索的数据

php - 我无法让 rewieer/TaskSchedulerBundle for Symfony 工作