.NET Wrapper for Google's New reCaptcha API

Google announced on their blog that they introduced a new version of reCaptcha API. As it’s fairly new, not many wrapper library has not been developed. Google has only introduced the official wrapper library in PHP for the new version. In this post, even though it’s not officially recognised by Google, I’ll introduce a .NET wrapper library for reCaptcha API.

NuGet Package














Aliencube.ReCaptcha.NET Aliencube.ReCaptcha.NET.MVC

Its GitHub repository can be found at: https://github.com/aliencube/ReCaptcha.NET Build status

How It Works

This library is very intuitive for use. If you are developing an ASP.NET MVC web app, all you need is download two NuGet packages stated above and use them. Let’s start from the basic usage.

Basic Usage

First of all, we need a controller to handle the reCaptcha input.

[HttpPost]
public virtual async Task<ActionResult> Index(HomeReCaptchaViewModel form)
{
  var vm = form;

  using (var settings = ReCaptchaV2Settings.CreateInstance())
  using (var reCaptcha = new ReCaptchaV2(settings))
  {
    var result = await reCaptcha.SiteVerifyAsync(this.Request.Form, this.Request.ServerVariables);

    vm.Success = result.Success;
    vm.ErrorCodes = result.ErrorCodes;
  }

  return View(vm);
}
`</pre>

As you can see, `ReCaptchaV2.SiteVerifyAsync()` takes parameters of `Request.Form` and `Request.ServerVariables`. This is all you need to do in controllers. For views, do the following codes:

<pre>`@using (Html.BeginForm(MVC.Home.ActionNames.Basic, MVC.Home.Name, FormMethod.Post))
{
  ...

  @Html.ReCaptcha(new Dictionary&lt;string, object&gt;() { { "class", "[class names]" }, { "data-sitekey", Model.SiteKey } })

  ...
}

@section Scripts
{
  @Html.ReCaptchaApiJs(Model.ApiUrl)
}
`</pre>
  • @Html.Recaptcha() renders the reCaptcha control.
  • @Html.ReCaptchaApiJs() renders JavaScript for the reCaptcha control.

    That’s all. Too easy, huh?

    Advanced Usage

    You might want more control over the automatic rendering. In this case, you can use the RenderParameters class. Properties of the RenderParameters class can be found at: https://developers.google.com/recaptcha/docs/display#render_param.

    `@using (Html.BeginForm(MVC.Home.ActionNames.Advanced, MVC.Home.Name, FormMethod.Post))
    {

    @Html.ReCaptcha(new Dictionary<string, object>() { { “class”, “form-group” } }, new RenderParameters() { SiteKey = Model.SiteKey, Theme = RenderThemeType.Dark })


    }
    `

    Rendering api.js can be asynchronous. For this, you can add the ApiJsRenderingOptions enum like:

    @section Scripts
    {
      @Html.ReCaptchaApiJs(Model.ApiUrl, ApiJsRenderingOptions.Async | ApiJsRenderingOptions.Defer)
    }

    Callback Usage

    If you want to control completely by yourself, this callback approach will be suitable for you.

    `@section Scripts
    {
    var callback = “onLoadCallback”;
    var elementId = “recaptcha”;

    @Html.ReCaptchaApiJs(Model.ApiUrl,

    ApiJsRenderingOptions.Async | ApiJsRenderingOptions.Defer,
    new ResourceParameters()
    {
      OnLoad = callback,
      Render = WidgetRenderType.Explicit,
      LanguageCode = WidgetLanguageCode.Korean
    })
    

    @Html.ReCaptchaCallbackJs(callback,

    elementId,
    new RenderParameters()
    {
      SiteKey = Model.SiteKey,
      Theme = RenderThemeType.Dark
    })
    

    }
    `

    For this, the ResourceParameters class is used in ReCaptchaApiJs(). This enables to load callback function that is loaded by ReCaptchaCallbackJs(). As all rendering options are defined here, the actual HTML part look like:

    `@using (Html.BeginForm(MVC.Home.ActionNames.Advanced, MVC.Home.Name, FormMethod.Post))
    {

    <div class=”form-group” id=”@elementId”></div>


    }
    `

  • @Html.RecaptchaCallbackJs() renders JavaScript callback function for the reCaptcha control.

    Settings

    As you can see the above example codes, configuration settings needs to be instantiated first by calling:

    `var settings = ConverterSettings.CreateInstance();
    `

    Alternatively, the settings instance can be injected by any IoC container. The following code is, for example, using Autofac

    `var builder = new ContainerBuilder();
    
    ...
    
    builder.Register(p => ReCaptchaV2Settings.CreateInstance()).As<IReCaptchaV2Settings>();
    builder.RegisterType<ReCaptchaV2>().As<IReCaptchaV2>();
    
    ...
    
    var container = builder.Build();
    `

    This settings instance comes from either reCaptchaV2Settings section or appSettings section on App.config or Web.config. It firstly look for the reCaptchaV2Settings section and, if no reCaptchaV2Settings section is found, then look for the appSettings section.

    `<configuration>
      <configSections>
        <section name="reCaptchaV2Settings" type="Aliencube.ReCaptcha.Wrapper.ReCaptchaV2Settings, Aliencube.ReCaptcha.Wrapper" requirePermission="false" />
      </configSections>
    
      <reCaptchaV2Settings
        requestUrl="https://www.google.com/recaptcha/api/siteverify"
        apiUrl="https://www.google.com/recaptcha/api.js"
        siteKey="[YOUR_SITE_KEY]"
        secretKey="[YOUR_SECRET_KEY]" />
    </configuration>
    `

    If you want to simply use the appSettings section, you can do the following instead:

    `<configuration>
    <appSettings>

    &lt;add key="RequestUrl" value="https://www.google.com/recaptcha/api/siteverify" /&gt;
    &lt;add key="ApiUrl" value="https://www.google.com/recaptcha/api.js" /&gt;
    &lt;add key="SiteKey" value="[YOUR_SITE_KEY]" /&gt;
    &lt;add key="SecretKey" value="[YOUR_SECRET_KEY]" /&gt;
    

    </appSettings>
    </configuration>

Conclusion

So far, we have reviewed the ReCaptcha.NET library. It’s easy to use and well integrated with ASP.NET MVC apps. With this library, your app will be more secure from spamy bots.