Symfony Logout Handler

June 23, 2017 | 3 Comments | Programming | PHP Symfony2

Suppose we  want log some activities when user logout on website. So let’s take a look on Symfony Logout Handler which is built in in Securiy Bundle.

First of all we need to create Logout listener which should implements LogoutHandlerInterface. From third token argument we can receive user information and perform actions depends on this.

<?php
//AppBundle\Listener\LogoutListener.php
 
namespace AppBundle\Listener;
 
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
 
class LogoutListener implements LogoutHandlerInterface
{
 
    /**
     * @{inheritDoc}
     */
    public function logout(Request $request, Response $response, TokenInterface $token)
    {
        $user = $token->getUser();
    }
}

Then we should register service:

# AppBundle/Resources/config/services.yml
services:
    app.logout.listener:
        class: AppBundle\Listener\LogoutListener

Last step will be adding handler in our security configuration:

# app/config/security.yml
security:
    firewalls:
        default:
            logout:
                path: logout
                handlers: [app.logout.listener]

About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad
3 COMMENTS
viveka

How to add logout handler in symfony 4

houcem

thank you man !

erufenix

Thank you! man helped me create a custom logout for my project.

But LogoutHandlerInterface is deprecated for version 5.1. Do you know any example of Symfony \ Component \ Security \ Http \ Event \ LogoutEvent?

LEAVE A COMMENT