Slava Fomin II
Slava Fomin II

Reputation: 28611

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

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?

Upvotes: 2

Views: 434

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52483

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

Upvotes: 2

Related Questions