Symfony 4:在自定义控制器中注销用户

时间:2019-02-04 16:04:48

标签: php symfony

我已按照本教程操作,使应用程序可以简单地通过调用/ logout之类的路径注销用户(通过官方文档中所述的Security模块)。可以。

现在,我想在我自己的控制器中注销用户(仍通过doc“记住我”功能中的描述进行登录)(例如,在进行电子邮件验证之前,如果仍在另一个帐户下打开另一个会话)。 但是我的方法都不起作用,这让我发疯。我尝试了$ session-> clear(),$ session-> invalidate(),$ request-> getSession-> clear(),$ request-> getSession-> Invalidate()等,等等。没有任何效果。

所以我的问题是,请问:您如何做到的?我应该如何处理这种情况?它是否与“记住我”功能有关(也许是在另一个Cookie中管理?)?

预先感谢

1 个答案:

答案 0 :(得分:0)

您的猜测可能是对的,该问题可能与“记住我”功能有关,因为它将使用cookie而不是会话来存储令牌,而不是会话,因此需要其他LogoutHandler。

Symfony提供了多种方法来处理身份验证,并且根据您当前的设置,您将需要正确的LogoutHandler。

如果您不只是想将用户重定向到注销路径,那么解决您的问题将非常困难。我现在想到的“最佳”方法是,通过手动构建Request-object来模拟注销请求,然后使用它调度一个GetResponseEvent,以便触发LogoutListener。调度事件可能会产生怪异的副作用,因此您甚至可能想要直接触发侦听器。看起来可能像这样:

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class MyController
{
    private $kernel;
    private $logoutListener;

    public function __construct(HttpKernelInterface $kernel, LogoutListenerInterface $logoutListener)
    {
        $this->kernel = $kernel;
        $this->logoutListener = $logoutListener;
    }

    private function customLogout()
    {
        // This needs to be updated whenever the logout path in your security.yaml changes. Probably something you want to improve on.
        $request = Request::create('/logout');

        $event = new GetResponseEvent($this->kernel, $request);

        $this->logoutListener->handle($event);
    }

    public function someAction()
    {
        $this->customLogout();

        // Do whatever you want to do for your request
    }
}

我认为这不是一个好的解决方案,因为干扰安全系统本质上是危险的。直接调用LogoutListener并传递内核也有些困难。老实说,我什至不能百分百确定这是否可行,但这是我想出的最可能解决您问题的方法。您可能想重新考虑自己在做什么,并找到另一种方法。