如何使用javascript/jQuery验证google reCAPTCHA v2?

Mah*_*din 109 javascript asp.net jquery google-api recaptcha

我在aspx中有一个简单的联系表单.我想在提交表单之前验证reCaptcha(客户端).请帮忙.

示例代码:

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Test Form</title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
        <link rel="stylesheet" href="/resources/demos/style.css">
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
        <script>
            $("#cmdSubmit").click(function () {
                //need to validate the captcha
            });
        </script> 
    </head>
    <body>
        <form id="form1" runat="server">
            <label class="clsLabe">First Name<sup>*</sup></label><br />
            <input type="text" id="txtFName" name="txtFName" class="clsInput" /><br />
            <div class="g-recaptcha" data-sitekey="my_key"></div>
            <img id="cmdSubmit" src="SubmitBtn.png" alt="Submit Form" style="cursor:pointer;" />
        </form>
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

我想在cmdSubmit点击时验证验证码.

请帮忙.

Pal*_*jaa 93

客户端对reCaptcha的验证 - 以下对我有用:

"grecaptcha.getResponse();"如果在客户端未验证reCaptcha,则返回null,否则返回null以外的值.

Javascript代码:

var response = grecaptcha.getResponse();

if(response.length == 0)
    //reCaptcha not verified

else
    //reCaptch verified
Run Code Online (Sandbox Code Playgroud)

  • 这是不正确的.Captcha尚未经过JS验证,您需要通过后端代码将响应以及您的站点密钥和密钥提交给Google的服务器,以确定Captcha是否已成功应答.这个答案非常不正确. (88认同)
  • 对于那些说答案不正确的人,你甚至读过这个问题吗?问题和答案都清楚地指明了客户端 - 显而易见的目的是在向服务器发送发布请求以进一步验证之前检查验证码是否实际填充在客户端*中. (11认同)
  • Quote:当最终用户解决reCAPTCHA时,将在HTML中填充新字段(g-recaptcha-response).https://developers.google.com/recaptcha/docs/verify (8认同)
  • 但那不是全部@CoalaWeb!Quote:获得响应令牌后,**您需要使用以下API使用reCAPTCHA验证它**以确保令牌有效.[https://developers.google.com/recaptcha/docs/verify](https://developers.google.com/recaptcha/docs/verify) (6认同)
  • 您只能知道用户是否在客户端实际填写了它."g-recaptcha-response"的值将被填写,但需要发送给Google,以便他们检查回复是否有效.例如,通过图像匹配,您可以单击任何内容或单击任何内容,然后单击"提交".这不正确,但填写了'g-recaptcha-response'的价值.您可以使用AJAX进行验证,但请务必将密钥保存在服务器端代码中.简短的回答是服务器必须检查它是否有效,无论是使用AJAX还是使用完整表单发布. (4认同)

Pra*_*rma 60

使用此选项可以使用简单的JavaScript验证谷歌验证码.

这个代码在html主体:

<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
Run Code Online (Sandbox Code Playgroud)

这段代码放在head部分调用get_action(this)方法表单按钮:

function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
        document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案是错的.我想当你得到回复时,你必须向google发送参数(response + secretkey + ClientIp)进行验证.验证后.谷歌让我们成功或失败.在您的示例中,您不使用第二步.你能解释一下:你的私钥在哪里?你什么时候用? (22认同)
  • 你应该使用`===`和`!==`; 没理由不去. (4认同)
  • Mahmut是正确的,这个答案是危险错误和不完整的. (3认同)
  • 我认为这是更好的解决方案.这样,您就可以在表单提交处理程序中处理响应的验证.这似乎比尝试在captcha回调上处理它更合乎逻辑.我想这取决于您是在飞行中还是在提交时进行验证. (2认同)

Man*_*zar 27

简化保罗的答案:

资源:

<script src="https://www.google.com/recaptcha/api.js"></script>
Run Code Online (Sandbox Code Playgroud)

HTML:

<div class="g-recaptcha" data-sitekey="YOUR_KEY" data-callback="correctCaptcha"></div>
Run Code Online (Sandbox Code Playgroud)

JS:

var correctCaptcha = function(response) {
        alert(response);
    };
Run Code Online (Sandbox Code Playgroud)

  • 像许多其他错误的解决方案一样,你只是在这里得到令牌.在您使用密钥将其发送给Google之前,您尚未*验证*. (9认同)
  • 这真是一个简单而明确的回应! (6认同)
  • 这应该是接受的答案,因为它不需要覆盖渲染功能.至于纯粹在JS中的验证,我怀疑这是可能的,因为它需要将秘密密钥放入JS中,从而允许每个人全身心投入. (2认同)

小智 26

如果你在回调上渲染Recaptcha

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Run Code Online (Sandbox Code Playgroud)

使用空DIV作为占位符

<div id='html_element'></div>
Run Code Online (Sandbox Code Playgroud)

然后,您可以在成功的CAPTCHA响应上指定可选的函数调用

var onloadCallback = function() {
    grecaptcha.render('html_element', {
      'sitekey' : 'your_site_key',
      'callback' : correctCaptcha
    });
  };
Run Code Online (Sandbox Code Playgroud)

然后,recaptcha响应将被发送到'correctCaptcha'函数.

var correctCaptcha = function(response) {
    alert(response);
};
Run Code Online (Sandbox Code Playgroud)

所有这些都来自Google API说明:

Google Recaptcha v2 API备注

我有点不确定你为什么要这样做.通常,您会将g-recaptcha-response字段与您的私钥一起发送,以安全地验证服务器端.除非您想要重新启动提交按钮,直到重新成功或类似 - 在这种情况下,上述情况应该有效.

希望这可以帮助.

保罗


imj*_*osh 10

我使用了HarveyEV的解决方案,但误读了它并使用jQuery validate而不是Bootstrap验证器.

  <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
  <script>
    $("#contactForm").validate({
      submitHandler: function (form) {
        var response = grecaptcha.getResponse();
        //recaptcha failed validation
        if (response.length == 0) {
          $('#recaptcha-error').show();
          return false;
        }
          //recaptcha passed validation
        else {
          $('#recaptcha-error').hide();
          return true;
        }
      }
    });
  </script>
Run Code Online (Sandbox Code Playgroud)


Tab*_*man 5

你可以使用以下代码渲染你的recaptcha

<div id="recapchaWidget" class="g-recaptcha"></div>

<script type="text/javascript">
   var widId = "";
   var onloadCallback = function ()
   {
    widId = grecaptcha.render('recapchaWidget', {
    'sitekey':'Your Site Key'
            });
   };
 </script>

 <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用"IsRecapchaValid()"方法验证您的recaptcha,如下所示.

 <script type="text/javascript">
     function IsRecapchaValid()
      {
      var res = grecaptcha.getResponse(widId);
      if (res == "" || res == undefined || res.length == 0)
         {
          return false;
         }
       return true;
      }
 </script>
Run Code Online (Sandbox Code Playgroud)


BV2*_*005 5

我认为所有这些都很棒,但我实际上让他们使用javascript和c#时遇到了麻烦.这就是我做的.希望它可以帮助别人.

//put this at the top of the page
<script src="https://www.google.com/recaptcha/api.js"></script>

//put this under the script tag
<script>
var isCaptchaValid = false;
function doCaptchaValidate(source, args) {
    args.IsValid = isCaptchaValid;
}
var verifyCallback = function (response) {
    isCaptchaValid = true;
};
</script>

//retrieved from google and added callback
<div class="g-recaptcha" data-sitekey="sitekey" data-callback="verifyCallback">

//created a custom validator and added error message and ClientValidationFucntion
<asp:CustomValidator runat="server" ID="CustomValidator1" ValidationGroup="Initial" ErrorMessage="Captcha Required" ClientValidationFunction="doCaptchaValidate"/>
Run Code Online (Sandbox Code Playgroud)


vch*_*kyi 5

不幸的是,没有办法仅在客户端(Web 浏览器)验证验证码,因为验证码本身的性质需要至少两个参与者(双方)来完成该过程。客户端 - 要求人类解决一些难题、数学方程式、文本识别,并且响应由算法以及一些元数据(例如验证码解决时间戳、伪随机挑战码)进行编码。一旦客户端提交带有验证码响应代码的表单,服务器端需要使用一组预定义的规则来验证该验证码响应代码,即 验证码是否在 5 分钟内解决,客户端的 IP 地址是否相同等等。这是一个非常笼统的描述,验证码如何工作,每一个实现(例如谷歌的ReCaptcha,一些基本的数学方程解决自制验证码),但唯一的一件事是共同的 - 客户端(网络浏览器)捕获用户的响应和服务器-side(网络服务器)验证此响应,以便了解表单提交是由人还是机器人提交的。

注意。客户端(Web 浏览器)可以选择禁用 JavaScript 代码的执行,这意味着所提出的解决方案完全无用。