Korzen
Bot Protection
In these docs

ASP.NET Core

Bot Protection in ASP.NET Core: the tag, Korzen's .NET package as middleware for the call, the visitor's IP behind a proxy, and the endpoint.

This guide is for ASP.NET Core 8 and later, with minimal APIs; in an MVC controller the middleware is the same. Korzen's package for .NET, Korzen.BotProtection, has no package dependency: a middleware on one HttpClient for the process, which keeps the connection open. It asks /v1/decide, gives up at your timeout and lets the visitor through on any error.

Payment, login and sign-up routes: turn on ProtectedAction = true, so a script that never loads your page cannot take the action. Protecting a checkout

The tag

Put the tag in the <head> of the layout your sign-up, sign-in and checkout pages use (Pages/Shared/_Layout.cshtml or Views/Shared/_Layout.cshtml):

<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>

For visitors whose network blocks Korzen's host, FirstParty = true serves the tag and its beacon from your own domain. First-party mode

The call

Behind Cloudflare? A Worker can do this without changing your app. Cloudflare Workers

Install the package from NuGet:

dotnet add package Korzen.BotProtection

Then, in Program.cs, the client and the middleware on the path that creates the account. It asks before your endpoint runs, answers a block itself, and leaves the answer in context.GetKorzenDecision(), or null when there is none:

// Program.cs
using Korzen.BotProtection;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKorzenBotProtection(o =>
{
    o.ApiKey = builder.Configuration["KORZEN_API_KEY"];
    o.Url = new Uri("https://eu.korzen.dev");
    // The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency
    o.Timeout = TimeSpan.FromMilliseconds(200);
});

var app = builder.Build();
app.UseWhen(c => c.Request.Path.StartsWithSegments("/signup"), branch =>
    branch.UseKorzenBotProtection(o =>
    {
        o.Ip = VisitorIp.LastForwarded; // one proxy of yours in front: see "The visitor's IP"
        o.ProtectedAction = true; // sign-up, login and payment: a script that never loaded your page holds no token; a page load spends none
        o.OnBlock = async (context, decision) =>
        {
            context.Response.StatusCode = 400; // the form's own error, so a bot learns nothing
            await context.Response.WriteAsync("We could not create your account.");
            return true;
        };
    }));

app.MapPost("/signup", async (HttpContext context) =>
{
    var user = await CreateAccount(await context.Request.ReadFormAsync()); // your own code
    await SaveRequestId(user, context.GetKorzenDecision()?.RequestId); // see "Apply the action"
    return Results.Redirect("/welcome");
});

app.Run();

The package also opens the client's connection when the app starts, so the first visitor does not wait for the TLS handshake. To ask without the middleware, inject BotProtectionClient: await client.DecideAsync(DecideRequest.From(context.Request, VisitorIp.LastForwarded(context)), context.RequestAborted) returns the Decision, or null on any error; it never throws. Kestrel keeps no order of the request's headers, so none is sent.

The visitor's IP

Without Ip, the middleware takes Connection.RemoteIpAddress, the connection's address, your proxy's if you have one. Behind one load balancer or nginx of yours, VisitorIp.LastForwarded takes the entry it added to X-Forwarded-For. Behind several proxies, call UseForwardedHeaders with XForwardedFor before the middleware instead, with your proxies in KnownProxies (or their networks in the known networks; loopback alone by default), and keep the default VisitorIp.Socket: it then reads the address the forwarded headers middleware set. Behind Cloudflare, pass VisitorIp.Cloudflare, which reads CF-Connecting-IP, if your server only takes traffic from Cloudflare.

Apply the action

The middleware applies action: on block it answers 403, or what your OnBlock writes, and your endpoint never runs. Make that answer the error the form shows when it fails for any other reason, so a bot learns nothing. The account starts in monitor mode, where action is always allow: nothing changes for visitors until you turn on block mode.

Keep the answer's request_id with what the action created, such as the account or the order: it names that decision when you ask us about it. The answer

Test it on your machine

Run dotnet run and open it on localhost. Pages on localhost always accept the tag and are never listed as a domain. Locally the IP is 127.0.0.1 or ::1, and that is fine.

  1. Set KORZEN_API_KEY in the environment (or with dotnet user-secrets set KORZEN_API_KEY …) and open the sign-up page. In the browser's developer tools, the _kz cookie appears after a few seconds.
  2. Sign up. The decision shows on the dashboard's Decisions page, under the path you sent.
  3. Check fail open: set a wrong key and sign up again. The call answers 401, and the sign-up goes through.

Common mistakes

  • A load balancer missing from KnownProxies. The middleware then ignores X-Forwarded-For, and every visitor has the balancer's private IP, which Bot Protection takes for no IP.
  • Clearing KnownProxies and the known networks to trust every hop. The IP becomes what the visitor wrote in X-Forwarded-For.
  • VisitorIp.LastForwarded after UseForwardedHeaders. That middleware moves the entries it read out of X-Forwarded-For, so the last one left is what the visitor wrote.
  • Calling /v1/decide from the browser. The API key would reach every visitor; the call belongs on your server.
  • A line in your log that starts korzen: the visitor's IP sent to Bot Protection. The client writes it once, at the first decision whose IP is your own network's (a load balancer's, a proxy's, a container's), which Bot Protection judges as no IP: set ip to the visitor's address (the visitor's IP). In Docker on your machine it is the bridge's address, and harmless there.