在FOSUser登录表单中验证ReCaptcha

时间:2016-08-08 15:31:07

标签: php symfony recaptcha

我正在使用FosUserBundleEWZRecaptchaBunde。 我重写了登录表单以添加recaptcha字段。一切正常。

问题是登录表单验证不考虑reCaptcha字段,如果用户输入正确的登录名和密码,他将被记录。

我做了一种 预登录 事件,应测试验证码是否有效,但我的 登录前 是一个扩展listener的{​​{1}},我真的不知道如何获取验证码值。

这是UsernamePasswordFormAuthenticationListener方法,在我的 预登录 监听器

中覆盖另一个方法
attemptAuthentication

protected function attemptAuthentication(Request $request) { // ... // I only have added this (return null everytime) $captcha = $request->get($this->options['recaptcha'], null, true); if ($captcha && true !== $captcha) { throw new BadCredentialsException('Invalid captcha.'); } // ... } 中,他们使用类似UsernamePasswordFormAuthenticationListener的内容来获取$username = $request->get($this->options['username'], null, true);username值。这将获得具有passwordinput名称的_username的值(这是在侦听器构造函数中定义的)。

我尝试使用与其他字段相同的方法来查找验证码值,但验证码字段是_password,里面有div,因此我每次都会iframe因为它没有找不到任何东西。

如何获取此验证码返回的值(true或false,我正在使用新的reCaptcha)? 我真的不知道如何找到这个值,当然这是可能的。

在登录表单中允许验证码验证可能不是一个好方法。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果您确实想要检查给定的重新访问代码是否有效,您可以创建自己的身份验证处理程序。该处理程序必须实现AuthenticationSuccessHandlerInterfaceAuthenticationFailureHandlerInterface

有两种方法需要实施: `

public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
    // validate captcha code
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
    // validate captcha code
}`

为了使用Session和Routing,您需要使用ContainerAware扩展处理程序类,然后通过类的构造函数注入这些服务。

将自定义处理程序注册为服务: `

...
    #app/config/security.yml
        security.authentication_handler:
            class: AppBundle\Handler\AuthenticationHandler
        public: false
        arguments:
            - @router
            - @session
        calls:
            - [ setContainer, [@service_container ] ]

要启用处理程序,请在security.yml file

中添加以下行

... form_login: success_handler: security.authentication_handler failure_handler: security.authentication_handler

您还可以考虑使用Google reCAPTCHA。