45 lines
1.7 KiB
Markdown
45 lines
1.7 KiB
Markdown
# 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 randomized text-image, selection, and one-click challenges with `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:
|
|
|
|
```text
|
|
dotnet add package CaptchaKit.AspNetCore --prerelease
|
|
```
|
|
|
|
Configure a distributed cache (Redis is recommended for more than one application instance), then add the service:
|
|
|
|
```csharp
|
|
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 a challenge and return its type, prompt, choices, and optional image in the format used by its UI:
|
|
|
|
```csharp
|
|
var challenge = await captcha.CreateAsync(cancellationToken);
|
|
var imageData = $"data:{challenge.ContentType};base64,{Convert.ToBase64String(challenge.ImageBytes)}";
|
|
```
|
|
|
|
Before completing the protected action, validate it once:
|
|
|
|
```csharp
|
|
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.
|