ThatSoftware<Dude>

Musings of a .NET Developer, CTO, Tech Enthusiasts

Captchas and reCaptchas are great inventions. They help keep spam out and help to verify that humans are on the interwebs and not mischievous bots buying up all of our concert tickets. Captchas were annoying for the most part and they always took 3-4 attempts to get right. reCaptchas were less annoying, and at the same time they also did an amazing thing. They helped to digitize text in books that was illegible for machines. But in the end they still kind of sucked a bit. There was always that 'a' that might of been a '9' or the 'i' that could of been a '1', 'l', '|' etc.

recaptcha
Old, but still awesome, ReCaptcha

Google has now solved that problem with their latest release of reCaptcha. This newest version is easier for humans and harder for bots to decipher. It uses a new risk detection engine to determine based on the users interactions with the Captcha how likely it is for them to be a bot. And if there is some doubt it does have secondary methods that it falls back to to determine it. And since I'm updating my websites currently to use this latest version, I figured I'd share the process with the peoples out there. So let's start.

no captcha recaptcha
Latest No Captcha reCaptcha

Get your keys


First thing before anything you'll need a set of secure keys in order to make requests to the reCaptcha API, and you can do that by going to https://www.google.com/recaptcha/ and clicking on the Get reCaptcha link. You'll need to register your domain and site owner first before you get started with the form below.

register site recaptcha

And immediately after you'll be greeted with 2 brand new keys to work with. You'll get a:


Site key: This is your public key and it will be specified on the front-end in your new widget.

Secret key: This key is solely for your eyes only and its the token that you will use to verify requests with the reCaptcha API.


Adding it to your site


Adding it to your website is a two step process. First you'll need to specify the following in the head section on your site.



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


And next stop you can add the following div wherever you want your new reCaptcha to show. Be sure to add the sitekey that you just received to the data-sitekey property in the div. The bottom example is just a random that one that wont work.



<div class="g-recaptcha" data-sitekey="6Lfsx4rtAAYHERAchhg1oKT46ctlzv9Y9HReK74g"></div>


And that's it! You now have a fully working reCaptcha on your webpage. The only thing left now is to verify the users response with Google.


Verifying a users answer


The new reCaptcha offers several different ways to go about verifying the users response. But I'll be showing how to do it by sending a simple POST request to Google with the users response. Once the form is submitted, the reCaptcha will add the g-recaptcha-response POST parameter to your parameter list, which is an encrypted string that will only work once and that you must send to Google to verify.


API Request URL



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


Url Parameters


secret: Required. The shared key between your site and ReCAPTCHA.

response: Required. The user response token provided by the reCAPTCHA to the user and provided to your site on.

remoteip: Optional. The user's IP address.


The Code



private bool CheckCaptcha()
{
        string url = "https://www.google.com/recaptcha/api/siteverify";
        WebRequest request = WebRequest.Create(url);
        string postData = string.Format("secret={0}&response={1}&remoteip={2}", ConfigurationManager.AppSettings["CaptchaSecretKey"], Request["g-recaptcha-response"], Request.UserHostAddress);
        
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postData.Length;

        StreamWriter writer = new StreamWriter(request.GetRequestStream());
        writer.Write(postData);
        writer.Close();

        StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream());
        string responseData = reader.ReadToEnd();
        
        JavaScriptSerializer jss = new JavaScriptSerializer();
        reCaptchaResponse cResponse = jss.Deserialize(responseData);
        return cResponse.success;
}



// define a new class to store our response, outside of the current class
public class reCaptchaResponse
{
    public bool success { get; set; }
}


API Response


Once we make the request, the response back should be in the following format. I went ahead and Deserialized it to a class that I generated, but if you were working with the JSON directly, then it would be in this format.



API Response

The response is a JSON object:

{
  "success": true|false,
  "error-codes": [...]   // optional
}


All we really need is the success flag, but if you want to show your users the specific error message you can also dive into the "error-codes" property. So if you have an old outdated user verification method, or no verification method at all, then maybe it's time to give Googles reCaptcha a try. Happy coding!

"sometimes you have to delete, to find your answer"
Copyright © 2017 ThatSoftwareDude.com
humans.txt