5

This is my ASP.NET form. I want to add invisible recaptcha to it with server side validation. Can someone please help?

I can do client side validation but it doesnt use secret key. My another questions is Do we need secret key for invisible recaptcha?

Please see serverside code that i used for google recaptcha but it is not working for Invisible recaptcha. I am getting this error : - 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 Code

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

Serverside Code

  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  }
 }

I am getting this error : - reCAPTCHA Error: missing-input-response: Not Valid Recaptcha

Satpal Singh
  • 121
  • 1
  • 2
  • 13
  • Invisible recaptcha? That does not make sense. Doesn't that defy the purpose of using it? – VDWWD Jun 29 '17 at 07:54
  • 2
    @VDWWD Please search Google Invisible reCaptcha https://developers.google.com/recaptcha/docs/invisible – Satpal Singh Jun 30 '17 at 00:03
  • ok... It does exists. Sorry about that. The only difference is that you do not have to click the checkbox, but the rest seems the same and if it still not trusts you it will still show the validation. – VDWWD Jun 30 '17 at 06:39
  • Be careful using `Response` as a variable name as there is also a Response object. Also check you are getting a value from `Request["g-recaptcha-response"]` – Jon P Jul 03 '17 at 00:01
  • Jon P i am not getting value from Request["g-recaptcha-response"] – Satpal Singh Jul 03 '17 at 00:17

2 Answers2

8

This is how I implemented the working sample:

-- Client Side (Refer to Google Documentation )

<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>

-- Server Side (keeps secret Key)

    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;

    }
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
Barsham
  • 749
  • 8
  • 30
0

I also have similar problem and it looks like it is harder to find any decent example. However, I saw that you have set data-callback="onSubmit" but I didn't see where you have defined that method. Is it there? Could that be what are you missing?

Xequtor
  • 125
  • 1
  • 12