首页 文章

为asp.net应用程序实现Invisible Google reCaptcha?

提问于
浏览
4

这是我的ASP.NET表单 . 我想通过服务器端验证为它添加不可见的recaptcha . 有人可以帮忙吗?

我可以做客户端验证,但它不使用密钥 . 我的另一个问题是我们是否需要秘密密钥来进行隐形重新检查?

请参阅我用于google recaptcha的服务器端代码,但它不适用于Invisible recaptcha . 我收到此错误: - reCAPTCHA Error: missing-input-response: Not Valid Recaptcha

<div id="ContactFormDiv" runat="server">
    <div class="form-row form-required">
        <asp:Label ID="YourNameLabel" runat="server" AssociatedControlID="YourNameTextBox"> Your Name:</asp:Label>
        <asp:TextBox ID="YourNameTextBox" runat="server" CssClass="form300" MaxLength="150"></asp:TextBox>
    </div>
    <div class="form-row form-required">
            <div id='recaptcha' class="g-recaptcha"
                data-sitekey="site key"
                data-callback="onSubmit"
                data-size="invisible">
            </div>
    </div>
    <div class="form-row-buttons">
        <asp:Button ID="SendMessageButton" ClientIDMode="Static" runat="server" Text="Send Message" CssClass="buttonPositive"
            CausesValidation="True" OnClick="SendMessageButton_Click" />
    </div>
</div>

Javascript代码

<script type="text/javascript" src="https://www.google.com/recaptcha/api.js" async defer></script>

Serverside代码

public class MyObject
{
    public string success { get; set; }
}

public static string ReCaptcha_Key = "------------------Site Key-----------------";
public static string ReCaptcha_Secret = "--------------Secret Key ---------------";

 public bool ValidateReCaptcha()
{
    bool Valid = false;
    //start building recaptch api call
    var sb = new StringBuilder();

    //Getting Response String Append to Post Method
    string Response = Request["g-recaptcha-response"];

    string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + Response;
    sb.Append(url);

    //make the api call and determine validity
    using (var client = new WebClient())
    {
        var uri = sb.ToString();
        var json = client.DownloadString(uri);
        var serializer = new DataContractJsonSerializer(typeof(RecaptchaApiResponse));
        var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        var result = serializer.ReadObject(ms) as RecaptchaApiResponse;

        //--- Check if we are able to call api or not.
        if (result == null)
        {
            lblmsg.Text = "Captcha was unable to make the api call";
        }
        else // If Yes
        {
            //api call contains errors
            if (result.ErrorCodes != null)
            {
                if (result.ErrorCodes.Count > 0)
                {
                    foreach (var error in result.ErrorCodes)
                    {
                        lblmsg.Text = "reCAPTCHA Error: " + error;
                    }
                }
            }
            else //api does not contain errors
            {
                if (!result.Success) //captcha was unsuccessful for some reason
                {
                    lblmsg.Text = "Captcha did not pass, please try again.";
                }
                else //---- If successfully verified. Do your rest of logic.
                {
                    lblmsg.Text = "Captcha cleared ";
                    Valid = true;
                }
            }
        }
    }
    return Valid;
}

public bool temp = true;
protected void SendMessageButton_Click(object sender, EventArgs e)
{
    temp = ValidateReCaptcha();
    if (temp == false)
    {
        lblmsg.Text = "Not Valid Recaptcha";
        lblmsg.ForeColor = System.Drawing.Color.Red;
    }
    else
    {
        lblmsg.Text = "Successful";
        lblmsg.ForeColor = System.Drawing.Color.Green;
    }

    Page.Validate();

    if (this.Page.IsValid == true && temp == true)
    { //Page and invisible recaptcha is valid  }
 }

我收到此错误: - reCAPTCHA Error: missing-input-response: Not Valid Recaptcha

2 回答

  • 0

    这就是我实现工作样本的方式:

    <head>
    	<!-- Google Invisible Captcha -->
    	<script src='https://www.google.com/recaptcha/api.js'/>
    	<script>
            function onSubmit(token) {
                document.getElementById("htmlForm").submit();
            }
    	</script>
    </head>
    <body>
    	<form id="htmlForm" action="Default.aspx" method="post">
    		<input name="txtName"  />
    		<input name="txtEmailAddress"  />
    		<button class="g-recaptcha btn btn-default"
                        data-sitekey="-------------------Site key--------------"
                        data-callback="onSubmit">
                        Submit Request
    		</button>
    	</form>
    </body>
    
    • 服务器端(保密密钥)
    public static bool IsValidCaptcha()
        {
    
            var secret = "--------------Secret Key ---------------";
            var req =
                (HttpWebRequest)
                    WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + secret + "&response=" + HttpContext.Current.Request.Form["g-recaptcha-response"]);
    
            using (var wResponse = req.GetResponse())
            {
    
                using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
                {
                    string responseFromServer = readStream.ReadToEnd();
                    if (!responseFromServer.Contains("\"success\": false"))
                        return true;
                }
            }
    
            return false;
    
        }
    
  • 4

    我也有类似的问题,看起来很难找到任何体面的例子 . 但是,我看到你设置了data-callback =“onSubmit”,但我没有看到你在哪里定义了该方法 . 它在那里吗?那可能是你错过了什么?

相关问题