Best Captcha for use in dotnet applications (DNTCaptcha)

Tohid haghighi
5 min readNov 8, 2023

--

This captcha is easy to use and very powerfull for your dotnet applications.

You can see this captcha source in github.

captcha

What is CAPTCHA?

CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a type of security measure known as challenge-response authentication. CAPTCHA helps protect you from spam and password decryption by asking you to complete a simple test that proves you are human and not a computer trying to break into a password protected account.

A CAPTCHA test is made up of two simple parts: a randomly generated sequence of letters and/or numbers that appear as a distorted image, and a text box. To pass a the test and prove your human identity, simply type the characters you see in the image into the text box.

What do captcha forms look like?

The original form of captcha tests, invented in the late 1990s, took the form of a panel of obscured letters or numbers. The letters were obscured by blurring, stretching or warping. It would then be the internet user’s task to identify these letters and type them into a separate area of the form. If they interpreted the letters correctly, they passed the test.

How do captcha tests work?

At present, computer programmes lack the sophistication that humans have when it comes to processing visual data. Human minds are hard-wired to pick up on patterns in everything they see. People often see patterns where they are none — such as a face in the moon or the outline of Elvis on a burnt bit of toast. This phenomenon is called pareidolia.

Computers, meanwhile, can be programmed to recognise letters and numbers. However, they stop recognising them when they are obscured or distorted too much.

What are the benefits of a captcha form?

Essentially captchas deter hackers from abusing online services because they block robot software from submitting fake or nefarious online requests.

Captcha tests can be used to…

  • Protect the integrity of online polls by stopping hackers using robots to send in repeated false responses.
  • Stop brute force attacks on online accounts in which hackers repeatedly try to log-in using hundreds of different passwords.
  • Prevent hackers from signing up for multiple email accounts that they’ll then go on to use for nefarious purposes.
  • Stop cyber criminals spamming blogs or news content pages with dodgy comments and links to other websites.
  • Prevent ticket touts from using robots to bulk buy tickets for shows and gigs.
  • To make online shopping more secure.

Install via NuGet

To install DNTCaptcha.Core, run the following command in the Package Manager Console:

PM> Install-Package DNTCaptcha.Core

You can also view the package page on NuGet.

  • To register its default providers, call services.AddDNTCaptcha(); method in your Program class.
using DNTCaptcha.Core;

namespace DNTCaptcha.TestWebApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDNTCaptcha(options =>
{
// options.UseSessionStorageProvider() // -> It doesn't rely on the server or client's times. Also it's the safest one.
// options.UseMemoryCacheStorageProvider() // -> It relies on the server's times. It's safer than the CookieStorageProvider.
options.UseCookieStorageProvider(SameSiteMode.Strict) // -> It relies on the server and client's times. It's ideal for scalability, because it doesn't save anything in the server's memory.
// .UseDistributedCacheStorageProvider() // --> It's ideal for scalability using `services.AddStackExchangeRedisCache()` for instance.
// .UseDistributedSerializationProvider()

// Don't set this line (remove it) to use the installed system's fonts (FontName = "Tahoma").
// Or if you want to use a custom font, make sure that font is present in the wwwroot/fonts folder and also use a good and complete font!
.UseCustomFont(Path.Combine(_env.WebRootPath, "fonts", "IRANSans(FaNum)_Bold.ttf")) // This is optional.
.AbsoluteExpiration(minutes: 7)
.RateLimiterPermitLimit(10) // for .NET 7x+, Also you need to call app.UseRateLimiter() after calling app.UseRouting().
.ShowThousandsSeparators(false)
.WithNoise(0.015f, 0.015f, 1, 0.0f)
.WithEncryptionKey("This is my secure key!")
.WithNonceKey("NETESCAPADES_NONCE")
.InputNames(// This is optional. Change it if you don't like the default names.
new DNTCaptchaComponent
{
CaptchaHiddenInputName = "DNTCaptchaText",
CaptchaHiddenTokenName = "DNTCaptchaToken",
CaptchaInputName = "DNTCaptchaInputText"
})
.Identifier("dntCaptcha")// This is optional. Change it if you don't like its default name.
;
});
}

Now you can add the ValidateDNTCaptcha attribute to your action method to verify the entered security code:

[HttpPost, ValidateAntiForgeryToken]
[ValidateDNTCaptcha(ErrorMessage = "Please enter the security code as a number.")]
public IActionResult Index([FromForm]AccountViewModel data)
{
if (ModelState.IsValid) // If `ValidateDNTCaptcha` fails, it will set a `ModelState.AddModelError`.
{
//TODO: Save data
return RedirectToAction(nameof(Thanks), new { name = data.Username });
}
return View();
}

Or you can use the IDNTCaptchaValidatorService directly:

namespace DNTCaptcha.TestWebApp.Controllers
{
public class HomeController : Controller
{
private readonly IDNTCaptchaValidatorService _validatorService;
private readonly DNTCaptchaOptions _captchaOptions;

public HomeController(IDNTCaptchaValidatorService validatorService, IOptions<DNTCaptchaOptions> options)
{
_validatorService = validatorService;
_captchaOptions = options == null ? throw new ArgumentNullException(nameof(options)) : options.Value;
}

[HttpPost, ValidateAntiForgeryToken]
public IActionResult Login2([FromForm]AccountViewModel data)
{
if (!_validatorService.HasRequestValidCaptchaEntry())
{
this.ModelState.AddModelError(_captchaOptions.CaptchaComponent.CaptchaInputName, "Please enter the security code as a number.");
return View(nameof(Index));
}

//TODO: Save data
return RedirectToAction(nameof(Thanks), new { name = data.Username });
}

Samples:

Different supported DisplayModes:

DisplayModeOutputNumberToWord

ShowDigits

SumOfTwoNumbers

SumOfTwoNumbersToWords

Please follow the DNTCaptcha.TestWebApp sample for more details.

--

--

Tohid haghighi
Tohid haghighi

Written by Tohid haghighi

Full-Stack Developer | C# | .NET Core | Vuejs | TDD | Javascript

No responses yet