Files
CaptchaKit/README.md
T
2026-09-12 08:14:34 +08:00

1.6 KiB

CaptchaKit

CaptchaKit is an ASP.NET Core CAPTCHA foundation with server-side, one-time validation and pluggable generators and storage.

CaptchaKit.Core has provider-neutral contracts. CaptchaKit.AspNetCore supplies a SkiaSharp text-image generator and IDistributedCache storage.

The package does not claim that image CAPTCHA alone defeats determined automation. Deploy it with rate limits, account lockout, and appropriate risk controls.

Quick start

Install both packages at the same version:

dotnet add package CaptchaKit.AspNetCore --prerelease

Configure a distributed cache (Redis is recommended for more than one application instance), then add the service:

builder.Services.AddStackExchangeRedisCache(options =>
    options.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddCaptchaKit(options =>
{
    options.CodeLength = 5;
    options.Lifetime = TimeSpan.FromMinutes(2);
    options.CacheKeyPrefix = "myapp:captcha:";
});

An endpoint can obtain an image challenge and return it in the format used by its UI:

var challenge = await captcha.CreateAsync(cancellationToken);
var imageData = $"data:{challenge.ContentType};base64,{Convert.ToBase64String(challenge.ImageBytes)}";

Before completing the protected action, validate it once:

if (!await captcha.VerifyAsync(request.CaptchaId, request.CaptchaCode, cancellationToken))
    return Results.Unauthorized();

VerifyAsync consumes the challenge on every attempt. Applications can replace ICaptchaGenerator or ICaptchaChallengeStore to use another challenge type or persistence backend.