implementing Invisible Google reCaptcha for asp.net application ?

Satpal Singh picture Satpal Singh · Jun 29, 2017 · Viewed 11.2k times · Source

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

Answer

Barsham picture Barsham · Sep 1, 2017

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;

    }