Adding Recaptcha to ASP.NET MVC with no baggage

When I decided to add recaptcha, to an email contact form, I naturally started looking online at options for completing the task. There were many routes I could have gone, but it seemed that most of the blog sources out there all pointed me to a nuget package, or to “go to codeplex and get this thing” . Then, when reviewing the documentation for those ‘helper’ projects, all of the processes seemed convoluted, and disappointing. I knew there had to be a simple, and pure, approach and so I decided to go to the source: Google.

Google is great at many things. I generally think their documentation is solid as well, but honestly, the docs for recaptcha are fairly weak. They contain all of the needed information, but in a way that is only slightly clearer than mud.

However, using what they gave me, and some creativity, I was able to arrive at a working solution. I will explain it all below:

Inserting the Captcha

First, as Google instructs you to do, add the following html where you want the captcha to appear. Along with the JavaScript (at the end of your html body). Note: Pay attention to the data-callback attribute that is not shown in Google’s example, but described in their surrounding text.

So that will actually show you the captcha if you try it just as it is. However, we have to validate it as well.

Working with the Captcha Client Side

In order to do that you really have a two step process. When the user interacts, the callback method you specify in that data-callback attribute is triggered. However, the value is simply an encoded response, and you will pass it back to the server as-is. To best accommodate this, I added a @Html.Hidden field to my page, and mapped it to a string property in my view model. Then, using the handleCaptcha() call back method, I set the response from Google into that hidden field.

So now you can present the captcha to the user, and capture the response contained in the call back, and send it to your controller for further validation. For this final validation you make a final api call (as described by Google) to get a yes or no answer.

Bringing it all back to the server to validate securely

For that I simply added a subroutine that returns a boolean, and call that in my controller passing the Google response string. Note: The response from the API call is a JSON object that .NET deserializes to a hashtable (technically a dictionary<string, object>). You find the “success key” and its value is your boolean success indicator.

That was it, it works exactly as I would have expected, and is quick and painless. I also added logic to disable my submit button until the captcha callback took place, that way the user couldn’t accidentally submit the form without that response.



Leave a Reply

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