So it seems that the battle between sites and bots is never ending. On the good side we have a proven warrior, CAPTCHA, invented by Captain John Cha, a decorated war hero in the french canadian robot war of 1983.
I’m not gonna go into real details about when and where you should use CAPTCHA controls, but in general it’s probably a good idea on any form that has the potential to be misused or abused by pesky bots or pesky non-bots (usually human). I like reCAPTCHA because its free and it makes me feel all warm inside that I’m helping a greater cause.
reCAPTCHA improves the process of digitizing books by sending words that cannot be read by computers to the Web in the form of CAPTCHAs for humans to decipher. More specifically, each word that cannot be read correctly by OCR is placed on an image and used as a CAPTCHA. This is possible because most OCR programs alert you when a word cannot be read correctly.
It’s pretty dead simple to get this thing going in MVC, as with most things in MVC, it’s just a different way of thinking instead of having a server (or user) control its probably best to implement it as an html helper. Keep in mind there are a good amount of ways to do this and there are ways to customize the display of the CAPTCHA that I’m not going to get into. Here’s a short list of things to do to get you started.
- Sign up for the free account with reCAPTCHA.
- Make sure you get your private and public keys.
- Get all fancy and create a settings class to handle all of your config options.
- Encapsulate the formatting and validation logic into its own class. Note that I’m using an HttpForm class to wrap the actual calls to the validation service. You will just need to create a WebRequest and execute a post. Most of this code is not unique and was either taken from some of the open source ASP.NET reCAPTCHA controls or other projects.
- You’ll notice that the generateHTML method is actually just creating the recommended html from their website which includes a noscript tag.
- Now for the MVC part create a extension method for HTML Helper. Yes there is a little structuremap going on here, you can ignore it since you aren’t using the HTTPForm abstraction class.
- On your view page put call this code inside of your form tags.
- Finally on your controller expect 2 form fields to be submitted and you’ll end up doing something like the following…
Obviously you’ll need to do something with that bool that you get back, you may decide to use the ModelState to return an error or redirect them to some other page. I apologize for not extracting some of the injection stuff and the HTTPForm class you will either need to create or just call WebRequest directly. I didn’t want to get into how to make a post request. Hope this helps you to get started in the right direction.