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

前端 未结 1 1636
时光取名叫无心
时光取名叫无心 2021-01-15 09:24

Symfony implements the functionality of logging user out and killing cookies. There is a LogoutListener which delegates those action to couple of logout handler

1条回答
  •  滥情空心
    2021-01-15 09:52

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

    0 讨论(0)
提交回复
热议问题