How to log user out of Symfony 2 application using it's internal handlers

假如想象 提交于 2020-01-11 06:43:55

问题


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.

Is it possible to do so?


回答1:


You can implement an extended logout-listener by overriding the default security.logout_listener service.

The default LogoutListener::requiresLogin(...) method only checks if the request-path equals a firewall's logout_path setting.

It looks like this:

protected function requiresLogout(Request $request)
{
    return $this->httpUtils->checkRequestPath(
        $request, $this->options['logout_path']
    );
}

Now let's assume you want to perform a logout if the session-parameter logout is set to true.

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);
    }

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

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);
     }
 }


来源:https://stackoverflow.com/questions/28828420/how-to-log-user-out-of-symfony-2-application-using-its-internal-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!