Google reCAPTCHA in HTML and JavaScript

This post is using two HTML pages that have only JavaScript enabled. Feel free to replace some of the code with JQuery if you are loading those scripts. Otherwise, you can implement Google reCAPTCHA in HTML and JavaScript.

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.

I’ve noticed during testing that it may be 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. Place the script call on your page, preferably in the header, but it doesn’t have to be if you use frames etc.
<script src="https://www.google.com/recaptcha/api.js" async defer> </script>

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

<div class="g-recaptcha"></div>

5. Create a javascript function that you can call to validate the CAPTCHA response from Google.

function VerifyCAPTCHA() {
	var response = grecaptcha.getResponse();

    alert(response);

    if(response.length == 0)
    {
        // reCaptcha not verified
        var textbox = document.getElementById('errortext');
        textbox.value = 'reCAPTCHA failed you BOT!';
        return false;
    }
    else
    {
		window.location.assign('http://www.yourdomain.com/MyResultsPage.html');
    }
};
6. Create the button that will validate your CAPTCHA on submit.
        <div>
            <input type="button" name="submitButton" value="Show Results!" onclick="javascript: VerifyCAPTCHA();" />
        </div>

A few things to note:
1) Notice that the button is of type “button”, not “submit”. This is because we’re going to depend on our VerifyCAPTCHA() function to redirect us on success.
2) You don’t need your Private/Secret key for this type of implementation.

Now when you run your page with the CAPTCHA on it, it will have to pass this response test before redirecting. On the page you’re redirecting to, you should have some code to verify that the referrer is your CAPTCHA page. This is because any BOT can look for window.location statements and follow them on their own, so you’ll want to stop deep linking in it’s tracks.

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.

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.

Google reCAPTCHA in .NET MVC

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 view, 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…” (Note, many MVC solutions may already have this installed)
    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 view, preferably in the header, but it doesn’t have to be if you use a _Layout view. I have it right after the @using and @model statements.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

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

@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
    <div class="g-recaptcha"></div>
}

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; }

	}
}

6. Create a private method in your controller to verify the reCAPTCHA

///
/// Check if the reCAPTCHA challenge was successful
///
private bool VerifyCaptcha()
{
	var response = Request["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(reply);

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

	return true;

}

7. Handle the checking in your [HttpPost] controller method for the view.

[HttpPost]
public ActionResult Create(Models.TaxWorksheetModel model)
{
	if (!ModelState.IsValid)
	{
		return View(model)
	}

	if (!VerifyCaptcha())
	{
		ModelState.AddModelError("", "There was an error validating the Captcha, please try again.");
		return View(model);
	}
	else
	{
		return RedirectToAction("Thanks");
	}
}

I’ll do my best to put up a post on how to debug this code in the near future. I hope that this post helps you to get up and running quickly with Google’s reCAPTCHA without the frustration that I had.

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.