tanveery / recaptcha-net

reCAPTCHA for .NET library lets you easily use Google's reCAPTCHA in an ASP.NET Web Forms / MVC / ASP.NET Core application.
Apache License 2.0
163 stars 69 forks source link
asp-net asp-net-core asp-net-mvc dotnet recaptcha recaptcha-api recaptcha-control recaptcha-extension recaptcha-library recaptcha-net recaptchav2

reCAPTCHA library for .NET

reCAPTCHA for .NET is one of the most popular and well-documented reCAPTCHA libraries used by thousands of .NET developers in their ASP.NET web applications. The library is created and maintained by @tanveery.

Highlights

The following are the highlights of the library:

How to Use reCAPTCHA for .NET: Step-by-Step

Creating a reCAPTCHA API Key

Before you can use reCAPTCHA in your web application, you must first create a reCAPTCHA API key (a pair of site and secret keys). Creating reCAPTCHA API key is very straight-forward. The following are the steps:

  1. Go to the Google's reCAPTCHA site.
  2. Click on the Admin Console menu option. You will be required to login with your Google account.
  3. In the Admin Console page, click on the Create button.
  4. Enter a label for your web application.
  5. Select reCAPTCHA v2 option and then "I'm not a robot" Checkbox sub-option from the reCAPTCHA Type list.
  6. Enter the domain of your web application, e.g. example.com. If you are creating this key for your localhost, just enter localhost. You can enter more than one domain which is useful if you want the key to work across different hosts.
  7. Accept the reCAPTCHA terms of service.
  8. Click on the Submit button.
  9. Copy your Site Key and Secret Key which you would need to specify in your application's web.config file.

Installation

The best and the recommended way to install the latest version of reCAPTCHA for .NET is through Nuget. From the Nuget's Package Manager Console in your Visual Studio .NET IDE, simply execute the following command:

PM> Install-Package RecaptchaNet

You can also download a released build of reCAPTCHA for .NET by going to the Releases section of this project.

Set Configuration

ASP.NET Web Forms / ASP.NET MVC 5

In the appSettings section of your web.config file, add the following keys:

<appSettings>
<add key="RecaptchaSiteKey" value="Your site key" />
<add key="RecaptchaSecretKey" value="Your secret key" />
</appSettings>

ASP.NET Core

In appsettings.json, add the following JSON properties:

"RecaptchaSiteKey": "Your site key",
"RecaptchaSecretKey": "Your secret key"

In the ConfigureServices method of the Startup class, add the following line of code:

using Recaptcha.Web.Configuration;
...
RecaptchaConfigurationManager.SetConfiguration(Configuration);

Render reCAPTCHA Widget

You can either use the Recaptcha.Web.UI.Controls.RecaptchaWidget web control (ASP.NET Web Forms) or call the RecaptchaWidget method of HTML helper (ASP.NET MVC 5 / ASP.NET Core) to render reCAPTCHA widget:

ASP.NET Web Forms

<%@ Register Assembly="Recaptcha.Web" Namespace="Recaptcha.Web.UI.Controls" TagPrefix="cc1" %>
...
<cc1:RecaptchaWidget ID="Recaptcha1" runat="server" />

ASP.NET MVC 5 / ASP.NET Core

@using Recaptcha.Web.Mvc;
...
@Html.RecaptchaWidget()

The above code by default renders both the API script as well as the widget. There are times when you want to render the API script and the widget separately such as the need to render multiple widgets on a page. The following is an example of how to achieve this:

ASP.NET Web Forms

<%@ Register Assembly="Recaptcha.Web" Namespace="Recaptcha.Web.UI.Controls" TagPrefix="cc1" %>
...
<cc1:RecaptchaApiScript ID="RecaptchaApiScript1" runat="server" />
<cc1:RecaptchaWidget ID="RecaptchaWidget1" RenderApiScript="false" runat="server" />
<cc1:RecaptchaWidget ID="RecaptchaWidget2" RenderApiScript="false" runat="server" />

ASP.NET MVC 5 / ASP.NET Core

@using Recaptcha.Web.Mvc;
...
@Html.RecaptchaApiScript()
@Html.RecaptchaWidget(rednderApiScript:false)
@Html.RecaptchaWidget(rednderApiScript:false)

Verify reCAPTCHA Response

When your end-user submits the form that contains the reCAPTCHA widget, you can easily verify reCAPTCHA response with few lines of code:

ASP.NET Web Form

if (String.IsNullOrEmpty(Recaptcha1.Response))
{
    lblMessage.Text = "Captcha cannot be empty.";
}
else
{
    var result = Recaptcha1.Verify();
    if (result.Success)
    {
        Response.Redirect("Welcome.aspx");
    }
    else
    {
        lblMessage.Text = "Error(s): ";
        foreach(var err in result.ErrorCodes)
        {
            lblMessage.Text = lblMessage.Text + err;
        }
    }
}

ASP.NET MVC 5 / ASP.NET Core

using Recaptcha.Web.Mvc;
...
RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
    ModelState.AddModelError("", "Captcha answer cannot be empty.");
    return View(model);
}
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
    ModelState.AddModelError("", "Incorrect captcha answer.");
}

Attributes

The attributes are used to control the behavior and appearance of the reCAPTCHA widget. They are specified in one of the three ways:

Assigning a value through method or property takes precedence over configuration. Of course, you don't need to set any attribute anywhere unless its requried. The following is the entire list of the attributes:

Attribute Description Type Values Default Value Configuration Key Required
Site Key Site key for reCAPTCHA. It is required for rendering the widget. String The site key associated with the site you register in Google reCAPTCHA Admin Console. No default value. Must be provided. RecaptchaSiteKey Yes
Secret Key Secret key for the reCAPTCHA. It is required for verifying reCAPTCHA response. String The secret key associated with the site you register in Google reCAPTCHA Admin Console. No default value. Must be provided. RecaptchaSecretKey Yes
APIVersion Determines the version of the reCAPTCHA API. String - 2 RecaptchaApiVersion No
Language Forces the reCAPTCHA widget to render in a specific language. By default, the user's language is used. String One of the values from the Language Codes list. User's language RecaptchaLanguage No
Size The size of the reCAPTCHA widget. RecaptchaSize enum Default, Normal, Compact Default RecaptchaSize No
TabIndex The tabindex of the reCAPTCHA widget. Int32 Any integer 0 - No
Theme The ccolor theme of the reCAPTCHA widget. RecaptchaTheme enum Default, Light, Dark Default RecaptchaTheme No
Use SSL Determines if SSL is to be used in Google reCAPTCHA API calls. RecaptchaSslBehavior enum AlwaysUseSsl, SameAsRequestUrl, DoNotUseSsl AlwaysUseSsl RecaptchaUseSsl No

Samples

The repo comes with three working samples that you can use to quickly understand and test the library:

Note: Before running these samples, please ensure that the site key and secret key are set in the web.config (.NET Framework) or appsettings.json (.NET Core) file.

Tooling

The current version of the repo is created using Microsoft Visual Studio 2019 Community Edition with .NET Framework 4.5 and .NET Core 3.1 as compilation targets.

Issues

If you find a bug in the library or you have an idea about a new feature, please try to search in the existing list of issues. If the bug or idea is not listed and addressed there, please open a new issue.