Symfony-如何在身份验证失败侦听器中获取用户名和IP地址?

bre*_*req 5 php symfony

我需要得到:

  • 用户名
  • IP地址

对于尝试登录我的网站的每个用户。如果用户成功登录,则获取该信息没有问题,但是我不知道如何获取IP地址以进行失败尝试。

她是我的代码:

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 }
Run Code Online (Sandbox Code Playgroud)

和听众:

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();
    }
Run Code Online (Sandbox Code Playgroud)

Kon*_*ski 5

注入RequestStack侦听器并从中获取Request信息。您可以从获得IPgetClientIp()

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

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