Google reCAPTCHA in .NET ASPX

This post is using Microsoft .NET in C# with Visual Studio Community 2015 edition.

Google reCAPTCHA
Google reCAPTCHA

Google has a client side implementation for their reCAPTCHA on your web pages. Their documentation is great at explaining what it is, but it lacks in specific examples for how to implement in different environments. This causes confusion with some developers when they paste the two lines of code in their web page, but they are still able to submit the page, even when they don’t fill in the CAPTCHA.

There are a few Nuget packages that have widget wrappers, but that’s not really necessary.

Another issue is that there is an older Version 1.0 and the newer 2.0 (“I’m not a robot”) implementation. I think most folks would prefer the newer one.

Also, I’ve noticed during testing that it may be easily possible to get through the CAPTCHA the first time. On subsequent requests, probably based on IP address, it creates a popup that you have to select photos from. That should stop most bot engines. Just mentioning so you don’t think there’s a problem if you still occasionally get a form submit that looks like it could be a bot.

The getting started section of the Google Developer’s Guide is fine for getting started, but I’ll still cover it here, as I strongly dislike blog posts that only show 80% of the solution.

First thing you need is the actual URL that your going to deploy the application on. So if you haven’t registered one yet, you should do that now. I don’t know how Google handles it when two people try to register the same domain with reCAPTCHA, but I would assume that it would be questioned at some level. Maybe I’ll do an investigation in the future when I’m bored. I just feel that I don’t want to setup a domain under my Google account and then find out later someone else registered the domain and I’ve made a potential problem for them.

Okay, so let’s get started:

  1. Register your domain, as previously mentioned.
  2. Sign up for your reCAPTCHA at Google.
    1. Save your site and private/secret key somewhere in your source control
  3. Right click on your solution and select “Manage NuGet Packages for Solution…”
    1. Click on “Browse”
    2. Search for “Newtonsoft.Json”
    3. Highlight it in the results
    4. Check the box next to your Web Application and click “Install”
  4. Place the script call on your page, preferably in the header, but it doesn’t have to be if you use master pages etc. I have it right after the asp:Content start key.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

NOTE: My IntelliSense in VS recognizes the two keywords “async” and “defer”, but still flags them with an HTML5 warning. You can ignore this.

5. WITHIN THE FORM TAGS of your page, place the widget. This is the “Implicit” method of displaying the reCAPTCHA widget.

<form runat="server" class="form-horizontal">
	<div class="g-recaptcha" data-sitekey="Site_Key_Provided_By_Google"><div>
<form>

6. Create a class to hold the response from Google

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace TimeTracker.web
{
	public class CaptchaResponse
	{

		[JsonProperty("success")]
		public bool Success { get; set; }

		[JsonProperty("error-codes")]
		public List<string> ErrorCodes { get; set; }

		[JsonProperty("challenge_ts")]
		public DateTime TimeStamp { get; set; }

		[JsonProperty("hostname")]
		public string HostName { get; set; }

	}
}
  1. Create a private method in your code behind to verify the reCAPTCHA
/// <summary>
/// Check if the reCAPTCHA challenge was successful
/// </summary>
/// <returns></returns>
private bool VerifyCaptcha()
{
	var response = Request.Form["g-Recaptcha-Response"];
	string secret = "Your_Private/Secret_Key_From_Google";

	var client = new WebClient();
	var reply = client.DownloadString(
				string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
								secret, response));

	CaptchaResponse captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);

	// Optionaly, look for messages if response is false, caution, response collection could still be null
	if (!captchaResponse.Success)
	{
		return false;
	}

	return true;

}
  1. Handle the checking in your button submit event
protected void btnSubmit_Click(object sender, EventArgs e)
{
	if (VerifyCaptcha())
	{
		Response.Redirect("Your_SubmitSuccessPage.aspx");
	}
	else
	{
		// Send shock to user's chair
	}
}

The version 1.0 of reCAPTCHA used to allow you to debug using localhost without issue. The new version doesn’t. I can only assume that this was done for security reasons.

Update: If you add localhost as an approved domain in the reCAPTCHA setup, you should be able to debug locally.

I hope that this post helps you to get up and running quickly with Google’s reCAPTCHA without the two or three hours of frustration that I had.