Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool



Using ReCaptcha with Asp.Net MVC

For all the debate regarding if Captcha's are a good thing or a bad thing one thing is certain (in my book).  If you do not have some way to stop spam-bots your site will become overridden with junk in a hurry.

In an effort to reduce the amount of spam comments I am getting over at Dimecasts.net I finally got off my lazy ass and worked on implementing a Captcha.  The solution I ended up going with was reCaptcha.  I found that their setup was very easy to use and worked right out of the box.  However, there was not a lot of information on the net on how to use reCaptcha within an MVC site, only Asp.Net Webforms.  So I thought I would share my experiences and explain how I implemented reCaptcha on Dimecasts.

Step 1 - Signup for and download the reCaptcha dll from their site

Step 2 - Add reference to the Recaptcha.dll to your project

Step 3 - Create an Action Filter to handle the Captcha validation

public class CaptchaValidatorAttribute : ActionFilterAttribute 
{
	private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
        private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
        
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY];
            var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY];
            var captchaValidtor = new Recaptcha.RecaptchaValidator
                                      {
                                          PrivateKey = -- PUT PRIVATE KEY HERE --,
                                          RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
                                          Challenge = captchaChallengeValue,
                                          Response = captchaResponseValue
                                      };

            var recaptchaResponse = captchaValidtor.Validate();

	    // this will push the result value into a parameter in our Action
            filterContext.ActionParameters["captchaValid"] = recaptchaResponse.IsValid;

            base.OnActionExecuting(filterContext);
        }
}

Step 4 - Implement the Controller Action that will handle the form submission and Captcha validation

[CaptchaValidator]
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult CreateComment( Int32 id, bool captchaValid )
{
.. Do something here
}

Step 5 - Create a Html Helper to build and render the Captcha control

      
public static string GenerateCaptcha( this HtmlHelper helper )
{
            
	var captchaControl = new Recaptcha.RecaptchaControl
        	{
	                ID = "recaptcha",
                	Theme = "blackglass",
        		PublicKey = -- Put Public Key Here --,
                        PrivateKey = -- Put Private Key Here --
		};

	var htmlWriter = new HtmlTextWriter( new StringWriter() );

	captchaControl.RenderControl(htmlWriter);

	return htmlWriter.InnerWriter.ToString();
}

Step 6 - Implement the logic in your view to actually render the Captcha control

<:%= Html.GenerateCaptcha() %>:

Step 7 - Oh wait, there is no step 7.  You are done.

There you go, that is all that is needed to setup reCaptcha for use in a MVC application

Till next time,

[ --- Remember to check out Dimecasts.net --- ]



Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# December 2, 2008 9:12 AM

Nick said:

You might also want to look at Akismet.  It's used with WordPress, but many other blog engines also use it.  I've had a very high success rate with catching spam using it, and it doesn't necessitate punching in CAPTCHA codes.

# December 2, 2008 10:52 AM

Derik Whittaker said:

@Nick,

I looked at that, but Dimecasts is on the border of being 'commercial' in their eyes and i am not willing to pay for that service right now.

# December 2, 2008 11:32 AM

Dew Drop - December 3, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - December 3, 2008 | Alvin Ashcraft's Morning Dew

# December 3, 2008 9:33 AM

ASP.NET MVC Archived Blog Posts, Page 1 said:

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# December 4, 2008 12:34 AM

Andrew said:

Have you tried this using Ajax to post the form? I'm wondering what it would take to pass the info from reCaptcha back to my controller when using jQuery.

# December 4, 2008 9:36 AM

Tuna Toksoz said:

How about using ModelState for invalid captcha,

filterContext.Controller.ViewData.ModelState.AddModelError()

I am planning to implement it this way, and blog about it (and you beat me to writing a blog post)

Cheers!

# December 8, 2008 5:06 PM

DotNetLinks.net said:

Track back from DotNetLinks.net

# December 17, 2008 1:52 PM

Integrating reCAPTCHA into a MonoRail project « Andy Pike said:

Pingback from  Integrating reCAPTCHA into a MonoRail project &laquo; Andy Pike

# January 4, 2009 4:54 PM

Kart Vijay said:

I tried adopting the above approach and for some reason the reCaptchaResponse.IsValid is always false and it gives the error code  "incorrect- captcha-sol" . I know the value i am entering is correct. Any thoughts?

# January 6, 2009 3:31 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Derik Whittaker

Derik is a .Net Developer/Architect specializing in WinForms working out the northern suburbs of Chicago. He is also believer and advocate for Agile development including SCRUM, TDD, CI, etc.

When Derik is not writing code he can be found spending time with his wife and young son, climbing on his bouldering wall, watching sports (mostly baseball), and generally vegging out. Check out Devlicio.us!

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News