【问题标题】:Symfony 4 : Logout a users in a custom controllerSymfony 4:在自定义控制器中注销用户
【发布时间】:2019-02-04 16:04:48
【问题描述】:

我已按照教程使应用程序能够通过调用 /logout 之类的路由(通过官方文档中描述的安全模块)来注销用户。它有效。

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

所以我的问题是:你是怎么做到的?我该如何处理这种情况?它是否与“记住我”功能有关(也许它在另一个 cookie 中进行管理?)?

提前致谢

【问题讨论】:

标签: php symfony


【解决方案1】:

您的猜测可能是正确的,该问题可能与记住我功能有关,因为这将使用 cookie 来存储令牌,而不是会话,因此需要不同的 LogoutHandler。

Symfony 提供了多种处理身份验证的方法,您将需要正确的 LogoutHandler(s),具体取决于您当前的设置。

如果您不只是想将用户重定向到注销路径,那么解决您的问题会非常困难。我现在能想到的“最佳”方式是通过手动构建请求对象来模拟注销请求,然后用它分派一个 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 并在内核中传递也有点不确定。老实说,我什至不能 100% 确定这会奏效,但这是我能想出的最接近您的问题的可能解决方案。您可能需要重新考虑自己在做什么并找到替代方法。

【讨论】:

    猜你喜欢
    • 2022-08-08
    • 2019-03-31
    • 2019-08-17
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2014-11-12
    • 2013-09-21
    • 2015-08-06
    相关资源
    最近更新 更多