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.

Author: Jack Yasgar

Jack Yasgar has been developing software for various industries for two decades. Currently, he utilizes C#, JQuery, JavaScript, SQL Server with stored procedures and/or Entity Framework to produce MVC responsive web sites that converse to a service layer utilizing RESTful API in Web API 2.0 or Microsoft WCF web services. The infrastructure can be internal, shared or reside in Azure. Jack has designed dozens of relational databases that use the proper primary keys and foreign keys to allow for data integrity moving forward. While working in a Scrum/Agile environment, he is a firm believer that quality software comes from quality planning. Without getting caught up in analysis paralysis, it is still possible to achieve a level of design that allows an agile team to move forward quickly while keeping re-work to a minimum. Jack believes, “The key to long term software success is adhering to the SOLID design principles. Software written quickly, using wizards and other methods can impress the business sponsor / product owner for a short period of time. Once the honeymoon is over, the product owner will stay enamored when the team can implement changes quickly and fix bugs in minutes, not hours or days.” Jack has become certified by the Object Management Group as OCUP II (OMG Certified UML Professional) in addition to his certification as a Microsoft Certified Professional. The use of the Unified Modeling Language (UML) provides a visual guide to Use Cases and Activities that can guide the product owner in designing software that meets the end user needs. The software development teams then use the same drawings to create their Unit Tests to make sure that the software meets all those needs. The QA testing team can use the UML drawings as a guide to produce test cases. Once the software is in production, the UML drawings become a reference for business users and support staff to know what decisions are happening behind the scenes to guide their support efforts.

2 thoughts on “Google reCAPTCHA in .NET ASPX”

  1. I followed this guide and am always getting “Missing Input Response” with a false in success.
    The only changes i made were replacing your placeholders with my private and public keys. any help would be greatly appreciated!
    I’m programming in ASP.Net C# Web Application.

    1. Hi Charles,

      That error means that the “response” is not being populated by the code in your code behind:

      var response = Request.Form[“g-Recaptcha-Response”];

      Or, your request is not populating it in the string properly:

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

      In the line above, the variables secret and response are replacing the {0} and {1} in the google URI in the string.Format argument.

      Make sure that the Request.Form argument is exactly as above. It might be tempting to replace the text above with “g-recaptcha” to match the code in the ASPX file, but that’s not what we’re trying to capture. I moved the recaptcha out from the FORM tags in my project and it still worked, even though it’s supposed to be within the form tags.

      If you double check that and it’s okay, then I’d suggest running the site in Chrome and pressing the “F12” key while you’re on your page. See if you see any errors in the Console tab while you’re going through the motions through submitting your form. If you see any that you can’t figure out, post them here.

Leave a Reply

Your email address will not be published. Required fields are marked *