Giter Site home page Giter Site logo

vahidn / dntcaptcha.core Goto Github PK

View Code? Open in Web Editor NEW
218.0 14.0 77.0 4.02 MB

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

License: Apache License 2.0

C# 10.36% CSS 0.05% Batchfile 0.12% TypeScript 0.81% JavaScript 22.09% HTML 29.55% SCSS 37.01%
captcha aspnetcore asp-net-core

dntcaptcha.core's Introduction

DNTCaptcha.Core

GitHub Actions status

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

dntcaptcha

Install via NuGet

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.

Linux (and containers) support

The SkiaSharp library needs extra dependencies to work on Linux and containers. Please install the following NuGet packages:

PM> Install-Package SkiaSharp.NativeAssets.Linux.NoDependencies
PM> Install-Package HarfBuzzSharp.NativeAssets.Linux

You also need to modify your .csproj file to include some MSBuild directives that ensure the required files are in a good place. These extra steps are normally not required but seems to be some issues on how .NET loads them.

<Target Name="CopyFilesAfterPublish" AfterTargets="AfterPublish">
    <Copy SourceFiles="$(TargetDir)runtimes/linux-x64/native/libSkiaSharp.so" DestinationFolder="$([System.IO.Path]::GetFullPath('$(PublishDir)'))/bin/" />
    <Copy SourceFiles="$(TargetDir)runtimes/linux-x64/native/libHarfBuzzSharp.so" DestinationFolder="$([System.IO.Path]::GetFullPath('$(PublishDir)'))/bin/" />
</Target>

Also you should use a custom font for Linux systems, because they don't have the Tahoma font which is defined by asp-font-name="Tahoma" by default.

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-too-many-requests-error-message="Too many requests! Please wait a minute!"
             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-too-many-requests-error-message="Too many requests! Please wait a minute!"
             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-too-many-requests-error-message="Too many requests! Please wait a minute!"
			 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 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().
                .WithRateLimiterRejectResponse("RateLimit Exceeded.") //you can instead provide an object, it will automatically converted to json result.
                .ShowThousandsSeparators(false)
                .WithNoise(0.015f, 0.015f, 1, 0.0f)
                .WithEncryptionKey("This is my secure key!")
                .WithNonceKey("NETESCAPADES_NONCE")
                .WithCaptchaImageControllerRouteTemplate("my-custom-captcha/[action]")
                .WithCaptchaImageControllerNameTemplate("my-custom-captcha")
                .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 });
        }
services.AddSwaggerGenWithConventionalRoutes();

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().

How to debug it!

If you can't run this library and the captcha image is not being displayed, first you should checkout the server's logs and at least you should see what's the response of the requested image. Open the network's tab of the browser's developer tools and see the responses. If you want to see the output of _logger.LogDebug, you should turn on this level of logging in the appsettings.json file. Also you can set the .ShowExceptionsInResponse(env.IsDevelopment()) option to simplify the debugging by showing the exceptions in the response body.

The Blazor based version!

If you have a Blazor based app, it's better to try DNTCaptcha.Blazor.

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

Angular

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

Pure JavaScript Usage

It's possible to use this captcha with a pure JavaScript 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

  • Don't use this setting, because it will destroy the encrypted part of the captcha's token:
 services.Configure<RouteOptions>(options => { options.LowercaseQueryStrings = true; });

dntcaptcha.core's People

Contributors

astrostrong avatar badrishchaudhari avatar bjarte avatar christophelav avatar danialfarzaneh avatar dependabot[bot] avatar engrajabi avatar eravse avatar ghalamborm avatar guerrerotook avatar haladamateusz avatar idemery avatar ipdotsetaf avatar mshadmehr avatar orbintsoft avatar rkarali avatar rufanov avatar sergeysolovyov avatar vahidn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dntcaptcha.core's Issues

NO Support for Distributed Systems

Summary of the issue

The library doesn't support distributed systems.
It's such a waste that a good library like this doesn't have this feature.

Probable Solution

I had a look at the source code and it seems that adding this feature doesn't need so much effort.
IMemoryCache has been used in two files:
MemoryCacheCaptchaStorageProvider and SerializationProvider
The latter one prevent any storage provider to work on distributed system.
I don't know what other changes is required but at least I know one part of the change required to support the feature is to just replace IMemoryCache with IDistributedCache.

مشکل با اعداد فارسی در سیستم عامل اندروید

سلام و عرض ادب
مشکلی که من باهاش برخورد کردم اینه که زمانیکه از طریق گوشی اندروید ارقام رو وارد میکنم اگه صفحه کلید در حالت فارسی باشه جواب نمیده(از عدد وارد شده خطا میگیره که با رشته عددی برابر نیست) ولی در حالت انگلیسی مشکلی نداره
با تشکر

don't refresh request

Hi

i found a problem in refresh button in identity page like Login or Register
do not fire request to refresh captcha image

image

an option to explicitly specify the http/https protocol for captcha image link generation (useful behind reverse proxies)

Summary of the issue

I understand that you have used Request.Scheme to generate the captcha image link, but this might not be effective behind reverse-proxies or load-balancers where the incoming https traffic is transformed into http to reach the application. Since this can result in "mixed content" warnings in modern browsers, I think some handy option like "PublicOrigin", as accomplished by the IdentityServer team, would make everyone happy:)

Environment

DNTCaptcha.Core version: 2.6.0
.NET Core SDK version: 3.1
IDE: VS2019

رفرش کد کپچا

با سلام
برای درخواست های که خروجی جی سان هست مقدار کپچا تغییر نمیکند . وقتی کد کپچا رو اشتباه وارد میکند دوباره کد تغییر نمی کند .با چه روشی کپچا رو رفرش کنیم .ممنون

return Json(new { success = false, state = "loginFail", responseText = messages });
من اونطوری فراخوانی کردم حالا نمیدونم روش کارم درسته یا خیر
$("#dntCaptchaRefreshButton").trigger("click");

Refresh do not work in ASP.NET core 3.0

Summary of the issue

When I click on refresh button url changes but captcha image do not change

Environment

DNTCaptcha.Core version: 
.NET Core SDK version:  3.0 

پیشنهاد ساختار جدید به همراه نویز

جناب نصیری سلام و عرض ادب من ساختار جدید رو ایجاد کردم میخواستم روی پروژه شما PR کنم متاسفانه نتونستم اگر ایرادی نداره من این بخش رو برای شما میفرستم در صورت تایید در نسخه بعدی به صورت پارامتر قرار بدید که به صورت ساده یا دارای نویز سپاس

[DNTCaptcha.Core-master.zip](https://github.com/VahidN/DNTCaptcha.Core/files/4270918/DNTCaptcha.Core-master.zip)

Can be used without AddMvc()?

Is it possible to use this library without adding full MVC (services.AddMvc() in Startup.cs)? for example i want to just use AddControllers()

DNTCaptcha.Core in Razor Page NOT WORKING

Summary of the issue

DNTCaptcha.Core in Razor Page NOT WORKING

Register.cshtml.cs

namespace MyProject.Areas.Identity.Pages.Account
{
    public class RegisterModel : PageModel
    {
        public async Task OnGetAsync(string returnUrl = null)
        { . . . }

        [ValidateDNTCaptcha(ErrorMessage = "Please enter the security code as a number.",
            CaptchaGeneratorLanguage = DNTCaptcha.Core.Providers.Language.English,
            CaptchaGeneratorDisplayMode = DNTCaptcha.Core.Providers.DisplayMode.SumOfTwoNumbers)]
        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        { 
		if (ModelState.IsValid) // => Always valid
		{ ... }
	}
}

Register.cshtml

<div class="col-lg-6 col-sm-12">
	<dnt-captcha asp-captcha-generator-max="90"
				 asp-captcha-generator-min="1"
				 asp-captcha-generator-language="English"
				 asp-captcha-generator-display-mode="SumOfTwoNumbers"
				 asp-use-relative-urls="true"
				 asp-placeholder="Security code as a number"
				 asp-validation-error-message="@_localizerShared["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" class="text-en" />
</div>
. . .
@section Scripts {
    <partial name="_ValidationScriptsPartial" />
    <script src="~/js/jquery.unobtrusive-ajax.min.js"></script>
}

ALWAYS VALID. How to use it in Razor Pages

نمایش کد بعد ازچند بار اشتباه زدن

با سلام
دنبال روشی هستم که با چند بار اشتباه زدن کد کپچا فوق نمایش داده شود.همون اول کد کپچا نمایش داده نشود. کد فوق چند قابلیتی دارد.؟ با تشکر

مشکل در دکمه refresh

سلام، این مشکل قبلا توسط #15 گزارش داده شده و شما هم راه حلش رو ارائه دادید.
منتها از اونجا که برای من هم مجدد پیش اومد و مدت زمانی طول کشید تا در نهایت به قسمت ایرادات مخزن سر زدم و متوجه راه حل رفع کردنش شدم، جهت صرفه جویی در وقت سایر برنامه نویسان که ممکنه در آینده به این مشکل برخورد کنند بهتر هست که قسمت راهنمای پروژه رو به روز رسانی کنید.

با توجه به اینکه استفاده از نسخه CDN
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"></script>
باعث ایجاد مشکل میشه بهتر هست اون قسمت رو از راهنما حذف کنید، یا صریحا در راهنما اعلام کنید که ایجاد مشکل میکنه.

چند نکته:
1-نسخه
NPM
موجود هست میتونید به راهنما اضافه کنید. من با استفاده از
libman
اضافش کردم به پروژم بدون مشکل کار میکرد.
2-نسخه
cdnjs
در حال ایجاد شدن هست
3-آدرسی که برای پروژه
https://github.com/aspnet/jquery-ajax-unobtrusive/tree/master/dist
در راهنمای سایت گذاشتید خطای 404 میده،
به مخزن اصلی تغییرش بدید
https://github.com/aspnet/jquery-ajax-unobtrusive/

با تشکر

Captcha not work on macOS and docker

I used DNTIdentityCore and got 2 different error on macOs and Docker.

On macOs(latest Mono Installed already) :

Exception: The type initializer for 'System.Drawing.KnownColors' threw an exception.</h1> at System.Drawing.KnownColors.FromKnownColor(KnownColor kc) at System.Drawing.ColorConverter.StaticConvertFromString(ITypeDescriptorContext context, String s, CultureInfo culture) at System.Drawing.ColorConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at System.Drawing.ColorTranslator.FromHtml(String htmlColor) at DNTCaptcha.Core.Providers.CaptchaImageProvider.DrawCaptcha(String message, String foreColor, String backColor, Single fontSize, String fontName) at DNTCaptcha.Core.DNTCaptchaImageController.Show(String text, String rndDate, String foreColor, String backColor, Single fontSize, String fontName)

And on Docker (USE microsoft/aspnetcore-build:1.1.1) :

`info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method DNTCaptcha.Core.DNTCaptchaImageController.Show (DNTCaptcha.Core) with arguments (CfDJ8AUyVhOCtYhBqsBayGrsMEg6ZEKonj8Yu4zyLjktNB8GB1aWxuLw9zhe3cuRfPfMiOi/F2sTu/8TXeYBrtMG42XJ2TPsiPDrmOU19aetv6kfg+YXpQu7Jy3vFg1RG3I9gY0ugsP2zH5Cb5uu15Zr50A=, 636275045063773290, black, #ccc, 20, Tahoma) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
Executing HttpStatusCodeResult, setting HTTP status code 400
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action DNTCaptcha.Core.DNTCaptchaImageController.Show (DNTCaptcha.Core) in 0.3593ms
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method IdentityServerWithIdentityCore.Controllers.ErrorController.Index (IdentityServerWithIdentityCore) with arguments (400) - ModelState is Valid
fail: IdentityServerWithIdentityCore.Controllers.ErrorController[0]
Error 400 for GET /DNTCaptchaImage/Show

  Accept: image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5
  Accept-Encoding: gzip, deflate
  Accept-Language: en-us

Cookie: .AspNetCore.Antiforgery.c0metC3jpAQ=CfDJ8AUyVhOCtYhBqsBayGrsMEgQPLfXuennB5AZ9tcxb05LRvGuolVy-ESXwrTXZXhAoBPp-........`

observable error: HttpErrorResponse Bad Request

observable error: HttpErrorResponse

I use DNTCaptcha.Core Version="1.4.1" and call it in Startup.cs like this

 services.AddDNTCaptcha();

In my angular app use dnt-captcha component

When I run project angular show this error in console of browser

observable error:  HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://localhost:5000/DNTCaptchaApi/CreateDNTCaptcha", ok: false, …}

How can I solve this problem?

Reason of Invalidation

Hi,

It would be great if the default validator service could return the reason of invalidation.
I want to have a different error message when cookie is not valid. For example telling user that your login form has been expired.
Based on current validator service I don't have any ways to do this except writing my own validator service.
I think it's really essential for a validator service to return the reason if a captcha entry is not valid.

Thanks in advance

Reusability of Captcha during Expiration time

Summary of the issue

Each captcha has its specific hidden inputs (2 ones), id, and cookie and maybe other things that I don't know.
These combinations with their original answer make a captcha valid. Unfortunately, each captcha expires just when its expiration time reaches. This will results a situation that captcha will be reusable in all its expiration time (approximately 8 minutes).
Right behavior is that each time a captcha is checked, its token and all stuffs related must expire.

Example code/Steps to reproduce:

Save the cookie in your browser. Write right answer in value attribute of the main input and copy the parent div with all things within it.
During the expiration time, the captcha remains reusable and you can use these combinations (Cookie and HTML node) to validate all your requests.

Change font in captcha phrase

Hello
I can't define new font for captcha, and always read that from system fonts
asp-font-name="Vazir" not worked actually, although this font existed in styles and appended to my project.
where we can set new font?

Image Provider generates Empty captcha (Linux)

Summary of the issue

I have used this library on arch Linux before and it was working fine. yesterday i switch to Ubuntu 20.04 ( WSL2 windows 2004) and setup new development environment on my main machine everything is working fine except this library.
there is no exception but the output of DNTCaptchaImage/Show?... is a empty transparent Image!
i already installed libgdiplus library on ubuntu.
what possibly can cause this problem ? (look at attached image pls)

Environment

Wsl2 - Ubuntu 20.04

DNTCaptcha.Core version: 2.3.0 and 2.5.0
.NET Core SDK version:  3.1
IDE: vscode

Output:

unknown

Exception message: there is no exception

Captcha not work on windows based docker nano Server

I`m using DNTCaptcha 1.4.2 and ASP Core 1.1 when i deploy the project on window server which is using docker nano server i face with this exception and captcha image was not showing in project:

System.TypeInitializationException: The type initializer for 'System.Drawing.KnownColors' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Drawing.GDIPlus' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'gdiplus': The specified module could not be found. (Exception from HRESULT: 0x8007007E)at System.Drawing.GDIPlus.GdiplusStartup(UInt64& token, GdiplusStartupInput& input,GdiplusStartupOutput& output)at System.Drawing.GDIPlus..cctor()
--- End of inner exception stack trace ---
at System.Drawing.GDIPlus.RunningOnWindows() at System.Drawing.KnownColors..cctor()
--- End of inner exception stack trace ---
at System.Drawing.KnownColors.FindColorMatch(Color c)
at System.Drawing.ColorConverter.StaticConvertFromString(ITypeDescriptorContext context, String s, CultureInfo culture)at System.Drawing.ColorConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)at System.Drawing.ColorTranslator.FromHtml(String htmlColor)
at DNTCaptcha.Core.Providers.CaptchaImageProvider.DrawCaptcha(String message, String foreColor, String backColor, Single fontSize, String fontName)
at DNTCaptcha.Core.DNTCaptchaImageController.Show(String text, String rndDate, String foreColor,String backColor, Single fontSize, String fontName)
crit: DNTCaptcha.Core.DNTCaptchaImageController[1001]
DrawCaptcha error.

Bad Request - Request Too Long

با سلام و احترام
زمانی در یک صفحه نیاز به وجود کپچاهای زیادی باشد مرورگر با خطای زیر مواجه میشه
Bad Request - Request Too Long
و برای ادامه کار حتما باید کش مرورگر پاک بشه

Conflict with Content-Security-Policy

Environment

DNTCaptcha.Core version: 2.0.2
.NET Core SDK version: 2.2.0

If we enable Content-Security-Policy on our website , we will get an error because of DNTCaptcha (it refers to not to put script tag in your page ).

DNTCaptcha puts a script tag in the page .
Is there any way to solve this problem ?

Bypassing Captcha using Refresh button

Summary of the issue

Refresh button explicitly sets model properties from query strings and generates captcha based on it.
It results in a vulnerability that by using Min and Max properties in url of refresh button, we can generate our desired value and it will validate successfully.

Example code/Steps to reproduce:

See this data-ajax-url attribute of refresh button for example:
data-ajax-url="/DNTCaptchaImage/Refresh?rndDate=637025421369768143&FontName=Tahoma&FontSize=12&ForeColor=%231B0172&Language=Persian&Max=999&Min=100&Placeholder=%D8%AD%D8%A7%D8%B5%D9%84%20%D8%AC%D9%85%D8%B9%20%D8%A7%D8%B9%D8%AF%D8%A7%D8%AF%20%D8%A8%D8%A7%D9%84%D8%A7%20%D8%B1%D8%A7%20%D9%88%D8%A7%D8%B1%D8%AF%20%DA%A9%D9%86%DB%8C%D8%AF&TextBoxClass=text-box%20single-line%20mx-auto&TextBoxTemplate=%7B0%7D&ValidationErrorMessage=%D9%84%D8%B7%D9%81%D8%A7%20%DA%A9%D8%AF%20%D8%A7%D9%85%D9%86%DB%8C%D8%AA%DB%8C%20%D8%B1%D8%A7%20%D8%A8%D9%87%20%D8%B1%D9%82%D9%85%20%D9%88%D8%A7%D8%B1%D8%AF%20%D9%86%D9%85%D8%A7%D8%A6%DB%8C%D8%AF&ValidationMessageClass=text-danger&CaptchaToken=.dntCaptcha95e784a1ee6e1f5c8252046ba44a97965b0484985984548&RefreshButtonClass=glyphicon%20glyphicon-refresh%20btn-sm"

we can change it to this (Max=999&Min=999):
data-ajax-url="/DNTCaptchaImage/Refresh?rndDate=637025421369768143&FontName=Tahoma&FontSize=12&ForeColor=%231B0172&Language=Persian&Max=999&Min=999&Placeholder=%D8%AD%D8%A7%D8%B5%D9%84%20%D8%AC%D9%85%D8%B9%20%D8%A7%D8%B9%D8%AF%D8%A7%D8%AF%20%D8%A8%D8%A7%D9%84%D8%A7%20%D8%B1%D8%A7%20%D9%88%D8%A7%D8%B1%D8%AF%20%DA%A9%D9%86%DB%8C%D8%AF&TextBoxClass=text-box%20single-line%20mx-auto&TextBoxTemplate=%7B0%7D&ValidationErrorMessage=%D9%84%D8%B7%D9%81%D8%A7%20%DA%A9%D8%AF%20%D8%A7%D9%85%D9%86%DB%8C%D8%AA%DB%8C%20%D8%B1%D8%A7%20%D8%A8%D9%87%20%D8%B1%D9%82%D9%85%20%D9%88%D8%A7%D8%B1%D8%AF%20%D9%86%D9%85%D8%A7%D8%A6%DB%8C%D8%AF&ValidationMessageClass=text-danger&CaptchaToken=.dntCaptcha95e784a1ee6e1f5c8252046ba44a97965b0484985984548&RefreshButtonClass=glyphicon%20glyphicon-refresh%20btn-sm"

It will give us 999 and when we write 999 in input, it will validate successfully.
A hacker can easily bypass captcha this way.
Refresh controller action must not depend on anything received from client and must generate captcha independently based on sever-side values.

Error 500 without description

Summary of the issue

I'm trying to use this library but I'm facing an HTTP 500 error.
the expected behavior is a useful error message.

Environment

Linux

DNTCaptcha.Core version: 2.3.0
.NET Core SDK version: 3.1

Example code/Steps to reproduce:

example request headers:

:method: POST
:path: /DNTCaptchaApi/CreateDNTCaptcha
:scheme: https
accept: application/json, text/plain, /
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
content-length: 210
content-type: application/json;charset=UTF-8
origin: https://localhost:5001
pragma: no-cache
referer: https://localhost:5001/login
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin

example request payload:

{"backColor":"#f7f3f3","fontName":"Tahoma","fontSize":18,"foreColor":"#111111","language":"English","max":9000,"min":1,"useRelativeUrls":true,"displayMode":"NumberToWord","useNoise":true,"captchaToken":"token"}

I've added library API this way :

services.AddDNTCaptcha(options =>
    options.UseCookieStorageProvider() // -> 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. );

Output:

Error 500.

Exception message: none

did I miss something?

HTTP400: BAD REQUEST

Summary of the issue

سلام
روی دو تا پروژه ی ساده تازه ایجاد شده
net core 2.2 , net 4.8
تست کردم باز همین خطا رو داد

این دلیلش بود که تو باگ ایجاد شده قبلی جزییات نفرستادم

Environment

edge 44 , firefox 69 developer

DNTCaptcha.Core version:  1.9.2
.NET Core SDK version:  net core 2.2  , net framework 4.8
IDE: visual studio  16.2.3

Example code/Steps to reproduce:

paste your core code

Output:

HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax.
GET - https://localhost:44333/DNTCaptchaImage/Show/CfDJ8DB9vg-EjNhHuYHkC4MDpXn9FS2k-ZuzzPnJ3rx9b2LbtrW-LuVgUrzapIYMrdlJNA6n9s5JUjTAQE8RLmfu8fUFpXgzlSMJR7KcCT6l51xuadDw1-m-qBDI2MkcocksgVA1J5IQoCygwBam-7adM0UE2b5hDZ7ogXt7iFlU90zikYz9NPQpXlFz-UV5bPAF6_CMqytNTvtZDvBjv_WVLCrqcKJdUG68I2CcaM8mdvkBEt5OOyFOq4afytCQO5HUs7MNiRX228CBfiOvRmRQvToIJXLqYgMyN91joznk6VMFBA2f_i8rlIV_8NjE2HtUrRn-XkADFrNZ8DyJ_uVW9Skm308-DADunJhR12urEiRzKez_X1UEv7Z_t6MuANTk8AlU8NwOqKnTjh8zr7PDvljpYbgBeC2DkEGIWqOORK7nvzm9NOqfbYdKZLOI15TmCMF7hD2Al_2MfD-bhT9I1R_lTZbAz_OFdO-xTU16IO_jBbOGLTStryslYPNHrptoYg

Exception message:
The request could not be processed by the server due to invalid syntax.

Full Stack trace: نداره!

Use DNTCaptcha in Separated Service

با سلام ، به دلیل وجود GetSalt
امکان ایجاد کپچا توسط درخواست کاربر بامرورگر و درخواست اعتبار سنجی آن توسط یک اپلیکیشن دیگر وجود ندارد آیا امکان دارد که این کپچا بصورت یک سرویس مستقل فقط وظیفه ایجاد و اعتبار سنجی (درخواست از سرویس های دیگر) کپچا را داشته باشد؟

استفاده در bootstrap 4

سلام
در صورتی که بخوایم از کپچا در بوتسرپ نسخه 4 استفاده کنیم آیا امکانش وجود داره؟
با توجه به اینکه در نسخه 4 بوتسرپ ایکن های
glyphicon
دیگه وجود نداره و در کپچا هم امکان قرار دادن تمپلیت برای ایکن رفرش وجود نداره؟

refresh button not work

 <dnt-captcha asp-captcha-generator-max="999999"
                             asp-captcha-generator-min="1000"
                             asp-captcha-generator-language="Persian"
                             asp-captcha-generator-display-mode="NumberToWord"
                             asp-use-relative-urls="true"
                             asp-placeholder="عدد بالا"
                             asp-validation-error-message="لطفا عدد نوشته شده را به عدد وارد کنید"
                             asp-font-name="Tahoma"
                             asp-font-size="22"
                             asp-fore-color="#333333"
                             asp-back-color="#FFFFFF"
                             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='fe-icon-repeat'></i></span></span>{0}</div>"
                             asp-validation-message-class="text-danger"
                             asp-refresh-button-class="fas fa-redo btn-sm" />


    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"></script>

a suggest for Send Ajax Post Request

Multi-Part Forms

(function ($) {
    $.fn.serializefiles = function () {
        var obj = $(this);
        /* ADD FILE TO PARAM AJAX */
        var token = $(obj).find('input[name= "__RequestVerificationToken"]').val();
        var DNTCaptchaInputText = $(obj).find('input[name= "DNTCaptchaInputText"]').val();
        var DNTCaptchaText = $(obj).find('input[name= "DNTCaptchaText"]').val();
        var DNTCaptchaToken = $(obj).find('input[name= "DNTCaptchaToken"]').val();
        
        var formData = new FormData();
        $.extend(formData, { '__RequestVerificationToken': token });
        $.extend(formData, { 'DNTCaptchaInputText': DNTCaptchaInputText });
        $.extend(formData, { 'DNTCaptchaText': DNTCaptchaText });
        $.extend(formData, { 'DNTCaptchaToken': DNTCaptchaToken });

        $.each($(obj).find("input[type='file']"), function (i, tag) {
            $.each($(tag)[0].files, function (i, file) {
                formData.append(tag.name, file);
            });
        });
        var params = $(obj).serializeArray();
        $.each(params, function (i, val) {
            formData.append(val.name, val.value);
        });
        return formData;
    };
})(jQuery);

use:

$.ajax({
                    type: "POST",
                    url: 'YOUR-URL',         
                    data: ('form[name="YOUR-Form-Name"]').serializefiles(),
                    processData: false,
                    contentType: false,
                    success: function (data, status, xhr) {
                        if (xhr.status == 403) {
                            window.location = '/login'; //در حالت لاگین نبودن شخص اجرا می‌شود
                        }
                        else if (status === 'error' || !data) {
                            alert('error');
                        }
                        else {
                           alert('complate');
                        }
                    }
                });

Captcha not work under nginx proxy or https

`info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method DNTCaptcha.Core.DNTCaptchaImageController.Show (DNTCaptcha.Core) with arguments (CfDJ8AUyVhOCtYhBqsBayGrsMEg6ZEKonj8Yu4zyLjktNB8GB1aWxuLw9zhe3cuRfPfMiOi/F2sTu/8TXeYBrtMG42XJ2TPsiPDrmOU19aetv6kfg+YXpQu7Jy3vFg1RG3I9gY0ugsP2zH5Cb5uu15Zr50A=, 636275045063773290, black, #ccc, 20, Tahoma) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
Executing HttpStatusCodeResult, setting HTTP status code 400
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action DNTCaptcha.Core.DNTCaptchaImageController.Show (DNTCaptcha.Core) in 0.3593ms
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method IdentityServerWithIdentityCore.Controllers.ErrorController.Index (IdentityServerWithIdentityCore) with arguments (400) - ModelState is Valid
fail: IdentityServerWithIdentityCore.Controllers.ErrorController[0]
Error 400 for GET /DNTCaptchaImage/Show

I run my project in a docker container, if I bind a domain by nginx then use proxy_pass forward to the container, or add SSL through CDN service, the captcha will return 400 error. Maybe it results from ports or something else?

DNTCaptchaValidator does not validate get method

Hi,
I wanna use ValidateDNTCaptcha for a get method but when i do that whatever user enter in captcha input text box DNTCaptchaValidator consider that as true.

Is this part necessary in DNTCaptchaValidatorResult
image

Incompatibility with .net core 2.2

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
System.Collections.Generic.List.get_Item(int index)
Microsoft.AspNetCore.Mvc.Routing.UrlHelper.GetVirtualPathData(string routeName, RouteValueDictionary values)
Microsoft.AspNetCore.Mvc.Routing.UrlHelper.Action(UrlActionContext actionContext)
Microsoft.AspNetCore.Mvc.UrlHelperExtensions.Action(IUrlHelper helper, string action, string controller, object values, string protocol)
DNTCaptcha.Core.DNTCaptchaTagHelper.getCaptchaImageTagBuilder(string encryptedText)
DNTCaptcha.Core.DNTCaptchaTagHelper.Process(TagHelperContext context, TagHelperOutput output)
DNTCaptcha.Core.DNTCaptchaTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)

AspNetCore.Views_Account_Login.b__45_1() in Login.cshtml

                        <dnt-captcha asp-captcha-generator-max="9000"
                                     asp-captcha-generator-min="1"
                                     asp-captcha-generator-language="Persian"
                                     asp-placeholder="کد امنیتی به رقم (مانند: 1388)"
                                     asp-validation-error-message="لطفا کد امنیتی را به رقم وارد نمائید"
                                     asp-font-name="Tahoma"
                                     asp-font-size="18"
                                     asp-fore-color="#333333"
                                     asp-back-color="#ccc"
                                     asp-text-box-class="k-textbox"
                                     asp-text-box-template="<span class='k-textbox k-space-right w-100 border-danger'>{0}<span class='inputgroup-icon ms-Icon  ms-Icon--Lock'></span></span>"
                                     asp-validation-message-class="text-danger"
                                     asp-refresh-button-class="ms-Icon ms-Icon--Refresh btn-sm" />

problem with ajax post request

با سلام
ایا کد کپچا با درخواست های اژاکسی مشکل دارد
با این حطا مواجه شدم. با تشکر.

NotSupportedException: Your ViewModel should implement the DNTCaptchaBase class (public class AccountViewModel : DNTCaptchaBase {}).

حذف نشدن کوکی ها

سلام، روزتون بخیر
با هر بار لود شدن صفحه یک کوکی ساخته شده و به هیچ وجه حذف نمیشوند و باعث میشود حجم ریکوئست ها بالا رفته و پس از چندین بار وارد کردن اشتباه کپچا، کاربر دیگر قادر به مشاهده سایت نباشد
(Bad Request - Request Too Long)

screenshot 2

عدم نمایش کد امنیتی

با سلام من از کل کد های شما رو انتقال دادم و تمامی کلاس ها استفاده کردم و لی کد امنیتیرو نشون نمیده فقط من از Install-Package DNTCaptcha.Core استفاده نکرده از سورس کدها استفاده کردم. تمامی مراحل رو خط به خط اجرا کردم. ,ولی متاسفانه نمایش داده نمیشود.ایا قسمت خاصی رو باید بررسی کنم .ممنون

HTTP500: SERVER ERROR

Summary of the issue

بعد از مدتی که یه صفحه باز بمونه و بخوایم کیچا رو رفرش کنیم خطای 500 میده
اگر صفحه رو رفرش کنیم مشکلش حل میشه

Environment

DNTCaptcha.Core version: 1.9.5
.NET Core SDK version:  2.2, net 4.8
IDE: visual studio 16.2.5

Example code/Steps to reproduce:

paste your core code

Output:

Exception message:
HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.
(XHR)POST - https://localhost:44357/dntcaptchaimage/refresh?data=CfDJ8DB9vg-EjNhHuYHkC4MDpXnsMGLJrFpv28wEoOPJ_SLHKP2Uq4AJPgJuVy-laRJ855XyeXeRbmCL1y40xJuzIxjiMIS8S828y51HKbv2QiOmOuR-j7Wl1mUjCFJnoy2trtV-_O6xhBMtY1GQb-JYwAlsZOAyq1hjdV_Fybj6HGFk7sp0YdmM_ryfm2isuWPmRg

Full Stack trace:

System.NullReferenceException: Object reference not set to an instance of an object.
   at DNTCaptcha.Core.DNTCaptchaImageController.invalidateToken(DNTCaptchaTagHelperHtmlAttributes model)
   at DNTCaptcha.Core.DNTCaptchaImageController.Refresh(String data)
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware.<Invoke>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware.<ExecuteWithFilter>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

showdigit

Summary of the issue

با سلام هنگامی که بر روی تولید عدد قرار میدهیم بیش از 3 حرف را ویرگول قرار میدهد امکان حذف ویرگول وجود دارد؟

ظاهرا مربوط به فرمت متن میباشد

Environment

DNTCaptcha.Core version: 
.NET Core SDK version: 
IDE: 

Example code/Steps to reproduce:

 public string GetText(long number, Language language)
        {
            var text = string.Format(CultureInfo.InvariantCulture, "{0:N0}", number);
            return language == Language.Persian ? text.ToPersianNumbers() : text;
        }

Output:

Exception message:
Full Stack trace:

Auto-refresh after waiting few minutes do not work.

Summary of the issue

Refresh work when I click on the refresh button but after waiting for a few mins the image is still the same, and even I try to enter expected output as per the current image displayed it shows an invalid message.

Environment

DNTCaptcha.Core version: 2.3.0
.NET Core SDK version: 3.0

Validation Error Message

Please send better message to show when send wrong numbers:
this line

with this message :
"کد امنیتی وارد شده صحیح نمی باشد.به رقم وارد نمایید"

a suggest

خواندن توسط google lens

سلام جناب نصیری
من از این بسته برای یک وب سایت سازمانی استفاده کردم
امنیت سازمان بهم گفته که میشه با نرم افزار google lens کد رو خواند آیا راهی وجود داره که این اتفاق نیفته؟

RTL text direction issue on CentOS 7

I run my project on centos 7 and I've installed all dependencies you referred in README.md, the problem is that captcha image characters displaying on wrong direction.
Also i installed Tahoma and other RTL fonts and it didn't worked.
have you any idea to solve this?

Environment

The in-use version: DNTCaptcha.Core 1.4.4
Operating system: CentOS Linux 7
IDE: Published with Visual Studio 2017 (v15.6.5) on Windows 10

Captcha URL:

http://192.168.228.129:5000/DNTCaptchaImage/Show?text=CfDJ8LWca3Bj7zxDmnTo3VBV6aSizgT3jEfA3aTyeat07C8MaMVgW0Xv7lZCeoV3VHONnTrV8iR8wjQZz04t0dgMVb5E%2Bion2y%2BiAVXzd%2F4sJq%2Fk50Ycex6noL8hxdF6XnJ81IsX7jNRq93UAPc4OOvIb6oAzmm2RKo1dy1R4XjUh3GlLcny19aJ2YrAW6xntViwHg%3D%3D&rndDate=636692528396190703&foreColor=%23333333&backColor=%23ccc&fontSize=20&fontName=Tahoma

Output:

show

Cookie decryption problem with nginx reverse proxy

I'm using DNTCaptcha with ASP.NET Core API application that is behind nginx reverse proxy. It seems DNTCaptcha cannot decrypt the cookie correctly and always returns BadRequest result.
Do you have any idea what can be wrong or give me any lead to check?

this is what I got from logs :
isValidCookie:: 20 + 5��:���

req
con-log

Environment

Windows Server
ASP.NET Core 3.1
Nginx 1.7.10

DNTCaptcha.Core version:  2.5.0
.NET Core SDK version:  3.1.201
IDE: 

cookieValue IsNullOrWhiteSpace

سلام جناب نصیری
وقتتون بخیر
توی قسمت لاگ پروژه
asp.net identity core
خطا و هشدار زیر بسیار رخ می دهد.
w0
w1
w3

ممنون میشم راهنمایی بفرمایید دلیل رخ دادن موارد ذکر شده چیست
با تشکر

header is too long

Summary of the issue

Bad Request - Request Too Long
HTTP Error 400. The size of the request headers is too long.

it has chance to occur,when refresh the captcha

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.