Symfony2:如何在控制器中手动注销用户? [英] Symfony2: how to log user out manually in controller?

查看:26
本文介绍了Symfony2:如何在控制器中手动注销用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在控制器中做类似的事情来注销用户:

i would like to do something like that in controller to log user out:

$user = $this->get('security.context')->getToken()->getUser();
$user->logOut();

推荐答案

Symfony2 中的注销由所谓的注销处理程序处理,它只是一个列表程序,当 URL 匹配来自安全配置的模式时执行,即.如果 URL 是 /logout 则执行此侦听器.有两个内置的注销处理程序:

Logout in Symfony2 is handled by so called logout handler which is just a lister that is executed when URL match pattern from security configuration, ie. if URL is let's say /logout then this listener is executed. There are two build-in logout handlers:

  1. CookieClearingLogoutHandler 简单地清除所有 cookie.
  2. SessionLogoutHandler 使会话无效
  1. CookieClearingLogoutHandler which simply clears all cookies.
  2. SessionLogoutHandler which invalidates the session

你所要做的就是和上一个一样.您可以通过简单地调用来实现它:

All you have to do is the very same the last one does. You can achieve it by simply calling:

$this->get('security.context')->setToken(null);
$this->get('request')->getSession()->invalidate();

Symfony 2.6

$this->get('security.token_storage')->setToken(null);
$this->get('request')->getSession()->invalidate();

警告

这仅在记住我功能被禁用时才有效.在其他情况下,用户将在下次请求时通过记住我的 cookie 重新登录.

Warning

This will only work when remember me functionality is disabled. In other case, user will be logged in back again by means of a remember me cookie with the next request.

如果您使用记住我功能,请考虑扩展解决方案:https://stackoverflow.com/a/28828377/1056679

Please consider the extended solution if you are using remember me functionality: https://stackoverflow.com/a/28828377/1056679

这篇关于Symfony2:如何在控制器中手动注销用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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