如何在Symfony2中使用SwitchUserListener ?

时间:2022-09-15 20:12:35

I'm trying to do a redirect when a user impersonates another user.

当用户模拟另一个用户时,我正在尝试重定向。

For this I registered a service:

为此,我注册了一项服务:

ACME_listener.security_switch_user:
    class: ACME\CustomerLoginBundle\Listener\SecuritySwitchUserListener
    arguments:  [@service_container, @router, @security.context]
    tags:
        - { name: kernel.event_listener, event: security.switch_user, method: onSecuritySwitchUser }

My listener class looks like this:

我的侦听器类是这样的:

namespace ACME\CustomerLoginBundle\Listener;

use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Http\Firewall\ListenerInterface;

class SecuritySwitchUserListener implements ListenerInterface {
    public function __construct($appContainer, $router) {
        $this->router = $router;
        $this->appContainer = $appContainer;
    }

    public function onSecuritySwitchUser(SwitchUserEvent $event) {
       echo "im in here!";
      // this does get called

    }

    public function handle(GetResponseEvent $event) {
        echo "but not here :(";
        // this does not get called!
    }

}

Now the problem is that I can not redirect the user from within the onSecuritySwitchUser method. Returning a RedirectResponse does NOT work and the SwitchUserEvent does NOT have a setResponse() method.

现在的问题是,我不能从onSecuritySwitchUser方法中重定向用户。返回一个RedirectResponse不工作,而SwitchUserEvent没有一个setResponse()方法。

What do I have to do so that the handle() method does get called?

我需要做什么才能调用handle()方法呢?

1 个解决方案

#1


0  

I think that handle() is called from onSecuritySwitchUser(). But I can be wrong.

我认为处理来自onSecuritySwitchUser()()。但是我可以是错误的。

UPDATE

更新

You can overwrite the event with your own request :)

您可以用自己的请求覆盖事件:)

Look at:

看:

Symfony\Component\Security\Http\Firewall\SwitchUserListener

And then Dispach new SwitchUserEvent with overwritten request

然后使用overwrite请求将新的切换用户事件分配。

if (null !== $this->dispatcher) {
        $switchEvent = new SwitchUserEvent($request, $token->getUser());
        $this->dispatcher->dispatch(SecurityEvents::SWITCH_USER, $switchEvent);
}

Maybe that will help you.

也许这对你有帮助。

#1


0  

I think that handle() is called from onSecuritySwitchUser(). But I can be wrong.

我认为处理来自onSecuritySwitchUser()()。但是我可以是错误的。

UPDATE

更新

You can overwrite the event with your own request :)

您可以用自己的请求覆盖事件:)

Look at:

看:

Symfony\Component\Security\Http\Firewall\SwitchUserListener

And then Dispach new SwitchUserEvent with overwritten request

然后使用overwrite请求将新的切换用户事件分配。

if (null !== $this->dispatcher) {
        $switchEvent = new SwitchUserEvent($request, $token->getUser());
        $this->dispatcher->dispatch(SecurityEvents::SWITCH_USER, $switchEvent);
}

Maybe that will help you.

也许这对你有帮助。