Redirect Symfony2 LogoutSuccessHandler to original logout target

前端 未结 3 2031
攒了一身酷
攒了一身酷 2020-12-10 15:25

I need to modify my user object on logout. To do this, I have a security.yml that contains the following (amongst other things) -

#...
    logout:
        s         


        
3条回答
  •  鱼传尺愫
    2020-12-10 16:20

    So, I think I've figured out the right answer -

    Rather than implementing LogoutSuccessHandlerInterface and configuring a logout.success_handler, my security.yml now looks like this -

    # ...
    logout:
        handlers: [my.bundle.security.logout_handler]
    # ...
    

    ...and I'm implementing Symfony\Component\Security\Http\Logout\LogoutHandlerInterface. Confusing naming, but this seems to be the preferred way of doing post-logout operations without having to get involved with the response object. My implementation looks like this -

    namespace My\Bundle\Security;
    
    use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
    use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpFoundation\Request;
    use Doctrine\ORM\EntityManager;
    
    /**
     * Do post logout stuff
     */
    class LogoutHandler implements LogoutHandlerInterface
    {
    
        /**
         * @var EntityManager
         */
        protected $em;
    
        /**
         * Constructor
         * @param EntityManager $em
         */
        public function __construct(EntityManager $em)
        {
    
            $this->em = $em;
        }
    
        /**
         * Do post logout stuff
         */
        public function logout(Request $request, Response $response, TokenInterface $authToken)
        {
            $user = $authToken->getUser();
    
            // do stuff with the user object...
            $this->em->flush();
    
            return $response;
        }
    }
    

    ...as you can see, the LogoutHandlerInterface provides a pre-made $response object that I can just return when I'm finished.

提交回复
热议问题