如何使用内部处理程序将用户注销到Symfony 2应用程序 [英] How to log user out of Symfony 2 application using it's internal handlers
问题描述
Symfony实现了注销用户并杀死cookie的功能.有一个LogoutListener
会将这些操作委派给几个注销处理程序:CookieClearingLogoutHandler
和SessionLogoutHandler
.
Symfony implements the functionality of logging user out and killing cookies. There is a LogoutListener
which delegates those action to couple of logout handlers: CookieClearingLogoutHandler
and SessionLogoutHandler
.
如果我们想手动使用户退出应用程序,我认为最好的做法是调用那些处理程序,而不要自己实现(复制)这样的低级逻辑.
If we want to log user out of application manually, I think the best course of action would be to call those handlers and not to implement (duplicate) such low-level logic yourself.
有可能这样做吗?
推荐答案
您可以通过覆盖默认的security.logout_listener
服务来实现扩展的注销侦听器.
You can implement an extended logout-listener by overriding the default security.logout_listener
service.
默认的LogoutListener::requiresLogin(...)
方法仅检查请求路径是否等于防火墙的logout_path
设置.
The default LogoutListener::requiresLogin(...)
method only checks if the request-path equals a firewall's logout_path
setting.
它看起来像这样:
protected function requiresLogout(Request $request)
{
return $this->httpUtils->checkRequestPath(
$request, $this->options['logout_path']
);
}
现在让我们假设如果会话参数logout
设置为true
,则要执行注销.
Now let's assume you want to perform a logout if the session-parameter logout
is set to true
.
因此,我们扩展了LogoutListener
类,并添加了带有其他逻辑的自定义requiresLogout()
方法.
Therefore we extend the LogoutListener
class and add our custom requiresLogout()
method with additional logic.
namespace Your\Name\Space;
use Symfony\Component\Security\Http\Firewall\LogoutListener;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class MyLogoutListener extends LogoutListener {
/**
* Whether this request is asking for logout.
*
* @param Request $request
*
* @return Boolean
*/
protected function requiresLogout(Request $request)
{
if ( $request->getSession()->get('logout') ) {
return true;
}
return parent::requiresLogout($request);
}
然后,我们只需在 config.yml
中使用我们的自定义类覆盖security.logout_listener.class
容器参数.
Afterwards we simply override thesecurity.logout_listener.class
container-parameter with our custom class in our config.yml
.
parameters:
security.logout_listener.class: \Your\Name\Space\MyLogoutListener
现在您可以像这样在...Controller
中注销用户:
Now you can logout a user inside a ...Controller
like this:
public function someAction(Request $request) {
// ... some logic here
if ($condition) {
$request->getSession()->set('logout', true);
}
}
这篇关于如何使用内部处理程序将用户注销到Symfony 2应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!