All Projects → VahidN → DNTCaptcha.Core

VahidN / DNTCaptcha.Core

Licence: Apache-2.0 license
DNTCaptcha.Core is a captcha generator and validator for ASP.NET Core applications

Programming Languages

SCSS
7915 projects
HTML
75241 projects
javascript
184084 projects - #8 most used programming language
C#
18002 projects
typescript
32286 projects
Batchfile
5799 projects
CSS
56736 projects

Projects that are alternatives of or similar to DNTCaptcha.Core

Home
Home for Blazor Extensions
Stars: ✭ 51 (-71.82%)
Mutual labels:  aspnetcore, asp-net-core
XAF Security E4908
This repository contains examples for Role-based Access Control, Permission Management, and OData / Web / REST API Services for Entity Framework and XPO ORM
Stars: ✭ 47 (-74.03%)
Mutual labels:  aspnetcore, asp-net-core
aspnetcore-authentication-apikey
Easy to use and very light weight Microsoft style API Key Authentication Implementation for ASP.NET Core. It can be setup so that it can accept API Key in Header, Authorization Header, QueryParams or HeaderOrQueryParams.
Stars: ✭ 215 (+18.78%)
Mutual labels:  aspnetcore, asp-net-core
MvcControlsToolkit.Core
Core Code for MvcControlsToolkit packages
Stars: ✭ 13 (-92.82%)
Mutual labels:  aspnetcore, asp-net-core
AspNetCore.Unobtrusive.Ajax
Unobtrusive Ajax Helpers (like MVC5 Ajax.BeignForm and Ajax.ActionLink) for ASP.NET Core
Stars: ✭ 46 (-74.59%)
Mutual labels:  aspnetcore, asp-net-core
Hexagonal-architecture-ASP.NET-Core
App generator API solution template which is built on Hexagnonal Architecture with all essential feature using .NET Core
Stars: ✭ 57 (-68.51%)
Mutual labels:  aspnetcore, asp-net-core
grandnode2
Free, Open source, Fast, Headless, Multi-tenant eCommerce platform built with .NET Core, MongoDB, AWS DocumentDB, Azure CosmosDB, LiteDB, Vue.js.
Stars: ✭ 626 (+245.86%)
Mutual labels:  aspnetcore, asp-net-core
Aspnetcoremultipleproject
ASP.NET Core API EF Core and Swagger
Stars: ✭ 189 (+4.42%)
Mutual labels:  aspnetcore, asp-net-core
PersianDataAnnotations
PersianDataAnnotations is ASP.NET Core MVC & ASP.NET MVC Custom Localization DataAnnotations (Localized MVC Errors) for Persian(Farsi) language - فارسی سازی خطاهای اعتبارسنجی توکار ام.وی.سی. و کور.ام.وی.سی. برای نمایش اعتبار سنجی سمت کلاینت
Stars: ✭ 38 (-79.01%)
Mutual labels:  aspnetcore, asp-net-core
BlazoredLocalStorage
This library has been moved to the Blazored org
Stars: ✭ 26 (-85.64%)
Mutual labels:  aspnetcore, asp-net-core
MvcSimplePager
Simple,lightweight,easy to expand pager for asp.net mvc and asp.net core,针对asp.net mvc 和 asp.net core 设计的通用、扩展性良好的轻量级分页扩展
Stars: ✭ 13 (-92.82%)
Mutual labels:  aspnetcore, asp-net-core
OnlineUsers-Counter-AspNetCore
Display online users count in ASP.NET Core in two ways (Cookie - SingalR)
Stars: ✭ 29 (-83.98%)
Mutual labels:  aspnetcore, asp-net-core
SeoTags
SeoTags create all SEO tags you need such as meta, link, twitter card (twitter:), open graph (og:), and JSON-LD schema (structred data).
Stars: ✭ 113 (-37.57%)
Mutual labels:  aspnetcore, asp-net-core
MinimalApi
ASP.NET Core 7.0 - Minimal API Example - Todo API implementation using ASP.NET Core Minimal API, Entity Framework Core, Token authentication, Versioning, Unit Testing, Integration Testing and Open API.
Stars: ✭ 156 (-13.81%)
Mutual labels:  aspnetcore, asp-net-core
Onion Architecture Asp.net Core
WhiteApp API solution template which is built on Onion Architecture with all essential feature using .NET 5!
Stars: ✭ 196 (+8.29%)
Mutual labels:  aspnetcore, asp-net-core
Inyector
Library to Implement Automatic dependency injection by Configuration over Scaned Assemblies
Stars: ✭ 13 (-92.82%)
Mutual labels:  aspnetcore, asp-net-core
Aspnetcore.identity.mongo
This is a MongoDB provider for the ASP.NET Core 2 Identity framework
Stars: ✭ 179 (-1.1%)
Mutual labels:  aspnetcore, asp-net-core
Aspnetcorelocalization
Localization.SqlLocalizer & ASP.NET Core MVC Localization Examples
Stars: ✭ 183 (+1.1%)
Mutual labels:  aspnetcore, asp-net-core
DNZ.SEOChecker
SEO Checker and Recommander Plugin (like wordpress Yoast) for ASP.NET Core.
Stars: ✭ 18 (-90.06%)
Mutual labels:  aspnetcore, asp-net-core
DNTScheduler.Core
DNTScheduler.Core is a lightweight ASP.NET Core's background tasks runner and scheduler
Stars: ✭ 44 (-75.69%)
Mutual labels:  aspnetcore, asp-net-core

DNTCaptcha.Core

GitHub Actions status

DNTCaptcha.Core is a captcha generator and validator for ASP.NET Core applications.

dntcaptcha

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.

Usage:

  • After installing the DNTCaptcha.Core package, add the following definition to the _ViewImports.cshtml file:
@addTagHelper *, DNTCaptcha.Core
  • Then to use it, add its new tag-helper to your view:

For bootstrap-3:

<dnt-captcha asp-captcha-generator-max="9000"
             asp-captcha-generator-min="1"
             asp-captcha-generator-language="English"
             asp-captcha-generator-display-mode="NumberToWord"
             asp-use-relative-urls="true"
             asp-placeholder="Security code as a number"
             asp-validation-error-message="Please enter the security code as a number."
             asp-font-name="Tahoma"
             asp-font-size="20"
             asp-fore-color="#333333"
             asp-back-color="#ccc"
             asp-text-box-class="text-box single-line form-control col-md-4"
             asp-text-box-template="<div class='input-group col-md-4'><span class='input-group-addon'><span class='glyphicon glyphicon-lock'></span></span>{0}</div>"
             asp-validation-message-class="text-danger"
             asp-refresh-button-class="glyphicon glyphicon-refresh btn-sm"
             asp-show-refresh-button="true"
             />

For bootstrap-4 (you will need Bootstrap Icons for the missing font-glyphs too):

<dnt-captcha asp-captcha-generator-max="9000"
             asp-captcha-generator-min="1"
             asp-captcha-generator-language="English"
             asp-captcha-generator-display-mode="NumberToWord"
             asp-use-relative-urls="true"
             asp-placeholder="Security code as a number"
             asp-validation-error-message="Please enter the security code as a number."
             asp-font-name="Tahoma"
             asp-font-size="20"
             asp-fore-color="#333333"
             asp-back-color="#ccc"
             asp-text-box-class="text-box form-control"
             asp-text-box-template="<div class='input-group'><span class='input-group-prepend'><span class='input-group-text'><i class='fas fa-lock'></i></span></span>{0}</div>"
             asp-validation-message-class="text-danger"
             asp-refresh-button-class="fas fa-redo btn-sm"
             asp-show-refresh-button="true"
             />

For bootstrap-5 (you will need Bootstrap Icons for the missing font-glyphs too):

<dnt-captcha asp-captcha-generator-max="30"
			 asp-captcha-generator-min="1"
			 asp-captcha-generator-language="English"
			 asp-captcha-generator-display-mode="NumberToWord"
			 asp-use-relative-urls="true"
			 asp-placeholder="Security code as a number"
			 asp-validation-error-message="Please enter the security code as a number."
			 asp-font-name="Tahoma"
			 asp-font-size="20"
			 asp-fore-color="#333333"
			 asp-back-color="#FCF6F5FF"
			 asp-text-box-class="form-control"
			 asp-text-box-template="<div class='input-group'><span class='input-group-text'><span class='bi-lock'></span></span>{0}</div>"
			 asp-validation-message-class="text-danger"
			 asp-refresh-button-class="bi-arrow-counterclockwise btn-lg"
			 asp-show-refresh-button="true"
			 asp-dir="ltr"
			 />
  • To register its default providers, call services.AddDNTCaptcha(); method in your Startup 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)
                .ShowThousandsSeparators(false)
                .WithNoise(pixelsDensity: 25, linesCount: 3)
                .WithEncryptionKey("This is my secure key!")
                .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.",
                    CaptchaGeneratorLanguage = Language.English,
                    CaptchaGeneratorDisplayMode = DisplayMode.NumberToWord)]
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(Language.English, DisplayMode.SumOfTwoNumbersToWords))
            {
                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 });
        }

How to choose a correct storage mode

If your environment is distributed and you are using a Session (UseSessionStorageProvider()) or Memory (UseMemoryCacheStorageProvider()) storage providers to store some temporary values, these values will not be distributed at all. By default, ASP.NET's session is maintained in the RAM of the running web server. However, for instance Windows Azure is a stateless platform, web role instances have no local storage; at any time the web role instance could be moved to a different server in the data center. When the web role instance is moved, the session state is lost. To have a perceived sense of state with a stateless protocol on a stateless web server, you need permanent server side storage that persists even if the web role instance is moved. In this case you should UseDistributedCacheStorageProvider() or at first try using the UseCookieStorageProvider().

Tips

  • If you are using the UseCookieStorageProvider() and also the CORS is activated, you should set the SameSiteMode to None: options.UseCookieStorageProvider(SameSiteMode.None) otherwise its default mode effectively disables CORS.
  • If you are using the Cloudflare, it doesn't like the SameSite cookies. So in this case try setting the SameSiteMode.None if the CookieStorageProvider is in use.
  • If your app is behind a reverse proxy, don't forget to add the forwarded headers middleware.
services.Configure<ForwardedHeadersOptions>(options =>
{
  options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  options.KnownProxies.Add(IPAddress.Parse("my load balancer ip 1"));
  options.KnownProxies.Add(IPAddress.Parse("my load balancer ip 2"));
});

Samples:

Different supported DisplayModes:

DisplayMode Output
NumberToWord dntcaptcha
ShowDigits dntcaptcha
SumOfTwoNumbers dntcaptcha
SumOfTwoNumbersToWords dntcaptcha

Please follow the DNTCaptcha.TestWebApp sample for more details.

SPA Usage:

It's possible to use this captcha with Angular 4.3+ apps too. Here is a sample to demonstrate it:

Supported Languages

Find all currently supported languages here. To add new language, kindly contribute by editing the following files:

How to use/create a different image provider

If you want to use another drawings library, you just need to implement the ICaptchaImageProvider service and register it as a singleton before adding services.AddDNTCaptcha. Your custom implementation will be used instead of the original one.

services.AddSingleton<ICaptchaImageProvider, MyCustomCaptchaImageProvider>();
services.AddDNTCaptcha();

Note:

  • You will need this NuGet.config file to restore the required dependencies.
  • Don't use this setting, because it will destroy the encrypted part of the captcha's token:
 services.Configure<RouteOptions>(options => { options.LowercaseQueryStrings = true; });
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].