DEVELOPMENT by Pedro Resende

Symfony On Login Failure Listener

Event Listeners How to

Post by Pedro Resende on the 20 of October of 2015 at 23:14

Today I'm going to explain how to create an event listener to record every login failure attempt.

To start, in your TestBundle, inside EventListener folder add a new class called OnLoginFailListener.

It will have the following appearance

<?php

namespace PedroResende\TestBundle\EventListener;

use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Description of OnLoginFailListener
 *
 * @author Pedro Resende <pedroresende@mail.resende.biz>
 */
class OnLoginFailListener implements AuthenticationFailureHandlerInterface
{

    private $router;
    private $session;
    private $container;

    /**
     * Constructor
     */
    public function __construct(RouterInterface $router, Session $session, $container)
    {
        $this->router = $router;
        $this->session = $session;
        $this->container = $container;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        // Whatever you would like to do ;)
        $request->getSession()->set(SecurityContextInterface::AUTHENTICATION_ERROR, $exception);
        return new RedirectResponse($this->router->generate('login'));
    }

}

on your Resources/config/service.yml file add

parameters:
    onloginfaillistener.class: PedroResende\TestBundle\EventListener\OnLoginFailListener
services:
    kernel.listener.authentication_failure_event_listener:
        class: %onloginfaillistener.class%
        arguments: [@router, @session, @service_container]

And that is it ;)