Showing posts with label captcha. Show all posts
Showing posts with label captcha. Show all posts

Friday, October 15, 2010

Adding reCAPTCHA with JavaScript

In some dynamic interfaces, you may not want to load reCAPTCHA with the initial page loaded. In others you can’t because it would expire by the time the user uses that piece of the UI.

In the above scenarios you can add reCAPTCHA just when you need it.

First include the recaptcha script:

<script type="text/javascript" src='http://www.google.com/recaptcha/api/js/recaptcha_ajax.js'></script>
If the page is served over https make sure to use that in the above url. Alternatively do it dynamically, like in asp.net MVC you can do:
<script type="text/javascript" src='<%= Request.Url.Scheme + 
"://www.google.com/recaptcha/api/js/recaptcha_ajax.js" %>'></script>
Add an empty div where you’ll want the reCAPTCHA to appear in the HTML.
In the corresponding JavaScript action, do:
Recaptcha.create(theRecaptchaPublicKey, targetDiv);
If you are using jQuery, one way is to retrieve it based on a css class like:
$('#someContainer .captcha').each(function () {
Recaptcha.create(theRecaptchaPublicKey, this);
});

Thursday, October 14, 2010

Adding reCAPTCHA to asp.net MVC

These are just a few steps, as the latest reCAPTCHA library has all the pieces you need for asp.net MVC:

  • Go to Get reCAPTCHA, which gives you the public and private keys you need to use reCAPTCHA with your site
  • Download the latest .net library at: http://code.google.com/p/recaptcha/downloads/list. Currently: dotnet-1.0.4.0
  • Add <%= Html.GenerateCaptcha()%> to the form you want to protect with the reCAPTCHA. Naturally you have to add the namespace for the extension to be recognized, some of the options:
    • Add the namespace to the web.config:
      <pages>
      <namespaces>
      ...
      <add namespace="Recaptcha" />

    • Add the namespace at the view:

      <%@ Import Namespace="Recaptcha" %>

    • Add your own extension method that wraps it. I changed the signature to return MvcHtmlString to prevent double encoding when using it with “<%:” instead of “<%=”

      public static MvcHtmlString GenerateCaptcha(this HtmlHelper htmlHelper)
      {
      var html = Recaptcha.RecaptchaControlMvc.GenerateCaptcha(htmlHelper);
      return MvcHtmlString.Create(html);
      }

  • Add the RecaptchaControlMvc.CaptchaValidator attribute to your controller. Also add parameters named captchaIsValid and captchaErrorMessage. Just like:

    [RecaptchaControlMvc.CaptchaValidator]
    public ActionResult MyMethod(Something else, bool captchaValid, string captchaErrorMessage)
    {
    // do something if (!captchaValid)
    }

  • Configure your keys. Some options:

    • Add to appsettings in the web.config, with entries named: RecaptchaPublicKey and RecaptchaPrivateKey
    • Set at Application Start:

      RecaptchaControlMvc.PrivateKey = privKey;
      RecaptchaControlMvc.PublicKey = pubKey;