breq breq - 4 months ago 37
PHP Question

Symfony - How to get username and IP address in authentication failure listener?

I need to get:


  • username

  • ip address



for each users that tries to log in to my website. There is no problem to get that information if user logged successfully but I don't know how to get IP address for failure attempts.

Her's my code:

app.listener.interactive_login_listener:
class: AppBundle\EventListener\LogonListener
arguments: ['@security.token_storage', '@doctrine.orm.entity_manager', '@security.authorization_checker', '@router', '@manager.settings']
tags:
- { name: kernel.event_listener, event: security.interactive_login, method: onAuthenticationSuccess }

# authentication failure event listener
app.listener.authentication_failure_event_listener:
class: AppBundle\EventListener\LogonListener
arguments: ['@security.token_storage', '@doctrine.orm.entity_manager', '@security.authorization_checker', '@router', '@manager.settings']
tags:
- { name: kernel.event_listener, event: security.authentication.failure, method: onAuthenticationFailure }


and the listener:

class LogonListener implements EventSubscriberInterface
{

private $_tokenStorage;
private $_em;
private $_authorizationChecker;
private $_router;
private $_settings;

public function __construct(
TokenStorage $tokenStorage,
EntityManager $em,
AuthorizationCheckerInterface $authorizationChecker,
Router $router,
$settings)
{
$this->_tokenStorage = $tokenStorage;
$this->_em = $em;
$this->_authorizationChecker = $authorizationChecker;
$this->_router = $router;
$this->_settings = $settings;
}

/**
* getSubscribedEvents
*
* @return array
*/
public static function getSubscribedEvents()
{
return array(
AuthenticationEvents::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess',
AuthenticationEvents::AUTHENTICATION_FAILURE => 'onAuthenticationFailure',
);
}

/**
* onAuthenticationSuccess
*
* @param InteractiveLoginEvent $event
*/
public function onAuthenticationSuccess(InteractiveLoginEvent $event)
{
var_dump( $event->getAuthenticationToken()->getUser() );
var_dump( $event->getRequest()->getClientIp() );
die();
}

public function onAuthenticationFailure(AuthenticationFailureEvent $event)
{
$userName = $event->getAuthenticationToken()->getUsername();
$user = $this->_em->getRepository('AppBundle:User')->findOneByUsername($userName);

var_dump( $user );
// how to get IP?
die();
}

Answer

Inject RequestStack into listener and get Request from it. You can get IP from getClientIp()

/**
 * @var RequestStack
 */
protected $requestStack;

/**
 * @return string
 */
protected function resolveClientIp()
{
    return $this->requestStack->getMasterRequest()->getClientIp();
}