How to use Google’s new reCaptcha in .NET

6 Comments
recaptcha

Google has replaced its old reCaptcha with a more sophisticated one, it tracks your mouse movements (and other stuff) to identify if you are a bot or not, if you are able to pass this first test by simply checking that “I’m not a robot”, then you’re lucky, if not, then you will have to type in the 2 words like old times to prove that you are human.


So back to our point, how can we use this new reCaptcha in a .NET application, same approach goes for any other technology…

Step1:

Head over to Google reCaptcha Admin Page, log in if necessary, then register a new website using the provided form.

Google reCaptcha : Register a new Website

You will receive a Site Key and a Secret Key, like these:

Google reCaptcha : Keys

Step 2:

Now that you have your keys, it’s time to place the widget inside our webpage, to do this, we need to add the following line before the closing head tag.

1
<script src='https://www.google.com/recaptcha/api.js'></script>

Now place the following markup wherever you want the reCaptcha box to appear, preferably some place inside a form tag.

1
<div class="g-recaptcha" data-sitekey="xxxxxxx"></div>

Make sure you replace xxxxxxx with your Site Key.

And here it goes:

Step 3:

So let’s say our reCaptcha is included in a form, where we also have other inputs such as Email, and a button to submit the form, we can receive the following query string for example if we use jQuery’s .serialize() function.

1
email=myemail@email.com&g-recaptcha-response=a-very-long-string-over-here

The g-recaptcha-response is automatically generated from the reCaptcha, and it contains a very long string that we must use to verify if validation was successful directly from Google.

After we submit the form, we make a request to our Handler that should capture that string.

We must make a GET request with some parameters to the following URL:

https://www.google.com/recaptcha/api/siteverify

Parameters:

secret

    this is the Secret Key of our application.

response

    • this is the Response

g-recaptcha-response

    that we got from the reCaptcha box

The response of this request will be a JSON string which contains a key “success” with a Boolean value of either True or False.

Assuming we have a Handler called ValidateRecaptcha.ashx, we can do the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
        public void ProcessRequest(HttpContext context)
        {
                //Set Response Content Type
                context.Response.ContentType = "plain/text";
                //Retrieve Request
                HttpRequest request = context.Request;
                //Retrieve Form Values
                String email = request.Form["email"];
                String recaptcha = request.Form["g-recaptcha-response"];
                //Verify reCaptcha via Webrequest to Google
                string postData =   "secret=" + 
                                    SecretKeyHere + 
                                    "&response=" + 
                                    recaptcha;
                WebRequest webRequest = "https://www.google.com/recaptcha/api/siteverify?" + postData);
                webRequest.Method = "GET";
                WebResponse webResponse = webRequest.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                var jsonObject = serializer.Deserialize<dynamic>(reader.ReadToEnd());
                bool isVerfied = jsonObject["success"];
                reader.Close();
                stream.Close();
                webResponse.Close();
                if (!isVerfied)
                {
                    //Validation was not successful!
                    context.Response.Write("Failure!");
                    return;
                }
                context.Response.Write("Success!");
                return;
        }

And that’s it!

Categories: Web Tags: Tags: , , , , , , ,

6 Replies to “How to use Google’s new reCaptcha in .NET”

  1. Sir ,
    i am creating own desktop (Window) application and when i am scrapping email than some time fetch this new google captcha.. so i am know how to solved this captcha pragmatically automatically solved and scrapped the email..
    Please sir guidance to me how to solve this google re-captcha fixed automatically and easly scrapped email …

  2. Could you please clarify
    Lines 1-34 I assume is added to your C# (.ascx.cs) file.

    “Assuming we have a Handler called ValidateRecaptcha.ashx, we can do the following:…”
    I have a view.ascx file that contains a submit button

    Calling the function found in my view.ascx.cs (C# Class) file
    protected void btnSubmitDonation_Click(object sender, EventArgs e)
    {
    // Test for ReCapture should go here I guess//
    CheckMyPayment();
    }
    If I test here then I don’t need to go any further if it fails right?

    Thanks

    1. ReCaptcha should be validated just like any other input in your form before doing the actual business, and this is done in the code above from the beginning to line 31, at that point if the response that you receive from Google servers is “False” then yes, you don’t need to go any further.

  3. Wow that was quick – Thanks

    So instead of ‘context’ as my object I will use ‘sender’.
    sender.Response.ContentType = “plain/text”;
    //Retrieve Request
    HttpRequest request = sender.Request;
    Right?

    1. The example above is based on a Handler while your code is based on a Controller and these are two different things, you don’t need to set a Content Type for the Response and you don’t need the HttpRequest object because I only used it to retrieve the values from the Form, because I call the Handler using a client side web request (JavaScript). You only need Line 11 to 25.

      1. Awesome – Thanks

        protected bool checkIfHuman()
        {
        string postData = “secret=” +
        SecretKeyHere +
        “&response=” +
        recaptcha;
        WebRequest webRequest = “https://www.google.com/recaptcha/api/siteverify?” + postData);
        webRequest.Method = “GET”;
        WebResponse webResponse = webRequest.GetResponse();
        Stream stream = webResponse.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        var jsonObject = serializer.Deserialize(reader.ReadToEnd());
        bool isVerfied = jsonObject[“success”];
        reader.Close();
        stream.Close();
        webResponse.Close();
        return isVerified;
        }

        protected void btnSubmitDonation_Click(object sender, EventArgs e)
        {
        bool isHuman = checkIfHuman();
        if(isHuman){
        CheckMyPayment();
        }else{
        //Display error
        }
        }

Leave a Reply

%d bloggers like this: