2017-05-05 117 views
0

我试图注册一个eventListener,它将在/ login_check尝试登录用户之前调用。我正在编写一个DDoS保护,iIlog数据库每次尝试(日期,user_id,is_failure),如果用户有超过N次错误的登录尝试,我生成一个通过电子邮件发送给正确的用户电子邮件的令牌。任何没有此令牌的人都将被禁止在10分钟内尝试另一次登录。在身份验证之前收听请求或在symfony3中重写/ login_check

要继续,我需要:

  • 要么能够在开始注册一个事件监听/ login_check
  • 或者是能够重写/ login_check添加事件

我没有发现任何有关“pre_authentication”的事件,你有解决方案吗?

我不会将存储库方法中的代码写入一个用户,它不是它的地方。

谢谢

回答

2

前几天我有类似的问题。就像你说我无法找到合适的“预认证”,在这一点上我甚至可以在尝试认证之前执行我的支票。 (AuthenticationSuccess和AuthenticationFailure处理程序在我的情况下不是一种选择,因为我想在尝试之前阻止尝试)

但最终我发现了一种方法,在我的情况下确实有效(尽管可能存在更好的但我找不到它)。

如果您的应用程序正在使用默认的用户名/密码认证,你可以这样做:

  1. 延长UsernamePasswordFormAuthenticationListener

    class UsernamePasswordFormAuthenticationListener extends \Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener 
    
    { 
        /** @var EntityManagerInterface */ 
        protected $entityManager; 
    
        /** 
        * setter is called through DI container 
        * 
        * @param EntityManagerInterface $entityManager 
        */ 
        public function setEntityManager(EntityManagerInterface $entityManager) 
        { 
         $this->entityManager = $entityManager; 
        } 
    
        /** 
        * 
        * @param Request $request 
        * 
        * @return null|RedirectResponse|\Symfony\Component\HttpFoundation\Response|\Symfony\Component\Security\Core\Authentication\Token\TokenInterface 
        */ 
        protected function attemptAuthentication(Request $request) 
        { 
         //do your logic and whatnot here 
         // i.E. return a redirect repsonse if the token is needed but missing 
    
         return parent::attemptAuthentication($request); 
        } 
    
    } 
    
  2. 覆盖在你的services.yml原来的服务

    security.authentication.listener.form: 
        class: AppBundle\Listener\UsernamePasswordFormAuthenticationListener 
        parent: security.authentication.listener.abstract 
        abstract: true 
        calls: [ [setEntityManager, ["@doctrine.orm.entity_manager"]] ] 
    

(这里使用setter注入,因为构造函数需要像一吨的参数)

也许这种方式可能适合您的需求,没有人有一个更好的主意

+0

这是完美的!因为我可以返回一个响应并将我的服务注入到监听器中,所以它非常完美。谢谢 ! ;) –