Human verification and access gate (EasyAdminBlazor.BotGuard)

An access gate for public deployments: let configurable search-engine crawlers and normal browsers through, make anonymous HTML requests solve a lightweight proof of work (PoW), and stop request floods with per-IP rate limiting plus a global concurrency cap. The goal is not to identify every bot, but to make every suspicious request pay a cost first and to block it before it reaches a Blazor circuit, the database or an AI call.

1. Scope

  • Application side only. Connection/frequency limits at nginx or IIS remain the first line and are out of scope.
  • It does not stop automation that runs a real browser; PoW only raises the per-request cost, while per-IP limiting and global concurrency are the actual backstop.
  • Off by default. When disabled the middleware calls next() immediately and behavior is byte-for-byte unchanged.
  • On multi-instance deployments each instance keeps its own limiter and caches; add a gateway/Redis layer for a cross-instance view.

2. Why an extension, and why the host must wire it explicitly

  1. Generic: every public deployment has this problem; it is not business-specific.
  2. Ordering: it must run after UseForwardedHeaders to see the real client IP and after UseAuthentication to let signed-in users through.
  3. The framework's EasyAdminAuthStartupFilter is an IStartupFilter; middleware it adds runs before every app.Use... in the host's Program.cs, and ClientIpResolver only reads Connection.RemoteIpAddress. It therefore cannot be auto-mounted there — the host calls UseEasyAdminBlazorBotGuard() explicitly.

3. Enabling

This extension is not published to the public NuGet feed; it is included for paid source-code licensees. For source integration use the ProjectReference below.

<ProjectReference Include="$(EabRoot)\Extensions\EasyAdminBlazor.BotGuard\EasyAdminBlazor.BotGuard.csproj" />
builder.AddEasyAdminBlazorBotGuard();

app.UseConfiguredForwardedHeaders(configuration);
app.UseAuthentication();
app.UseEasyAdminBlazorBotGuard();
app.UseAuthorization();

Configuration section BotGuard:

{
  "BotGuard": {
    "Enabled": true,
    "ChallengeDifficulty": 20,
    "CrawlerVerification": "ReverseDns",
    "RateLimit": { "Enabled": true, "PermitLimit": 120, "Window": "00:01:00" },
    "GlobalConcurrencyLimit": 150
  }
}

Every value has a default; Enabled defaults to false.

4. Decision order

  1. Enabled=false → pass through.
  2. Loopback address and ExemptLoopback=true → pass (local debugging, health checks).
  3. OPTIONS → pass.
  4. Non-static / non-health path → per-IP rate limit, otherwise 429.
  5. ProtectedPaths (default /_blazor, /hubs/): require a signed-in user or a valid challenge cookie, otherwise 403 (no HTML challenge — negotiation/WebSocket requests do not run JS).
  6. Signed-in user (ExemptAuthenticated) or a valid challenge cookie → pass.
  7. ExemptPaths (default /health, /robots.txt, /sitemap.xml, /favicon.ico, /.well-known/, /api/) and static assets → pass.
  8. UA matches a configured crawler rule → verify according to the configured strength; pass on success, continue on failure.
  9. Anonymous GET/HEAD with Accept containing text/html or */* → return the challenge page.
  10. Everything else → 403.

Short requests (excluding step 5 long-lived connections) must also pass the global concurrency gate before entering the downstream pipeline; otherwise 503.

5. Crawler rules

Built in:

Name UA token Reverse-DNS suffixes Official IP ranges
Bing bingbot search.msn.com https://www.bing.com/toolbox/bingbot.json
Baidu baiduspider baidu.com, baidu.jp No official machine-readable list

CrawlerVerification modes:

  • UserAgentOnly: trust the UA. Cheapest, but trivially spoofed; internal/temporary use only.
  • ReverseDns (default): PTR host must match a configured suffix, then forward resolution must return the same IP. A PTR claim alone is worthless — anyone can write one.
  • ReverseDnsAndIpRange: double DNS plus the official IP list; crawlers without a machine-readable list fall back to double DNS.

Crawlers appends rules or overrides a built-in one by Name:

{
  "Crawlers": [
    {
      "Name": "Google",
      "UserAgentContains": [ "googlebot" ],
      "ReverseDnsSuffixes": [ "googlebot.com", "google.com" ]
    }
  ]
}

With IncludeDefaultCrawlers=false only Crawlers is used.

Results are cached per rule + IP: 24 hours for success, 5 minutes for failure (so a transient DNS outage does not punish a real crawler for long). Concurrent requests for the same IP + rule trigger only one DNS lookup.

6. PoW challenge

  • The server signs v1|challenge|expires|difficulty with HMAC; the cookie is ticket.nonce.
  • The browser computes FNV-1a(challenge + ":" + nonce) until the result has the required number of leading zero bits, writes the cookie and reloads.
  • The server performs one hash check plus a constant-time signature comparison; the CPU cost sits on the client.
  • ChallengeDifficulty is clamped to 1–24, default 20 (about one million attempts; usually a few hundred milliseconds on desktop). Lower it to 16–18 if first visits feel slow.
  • Cookie lifetime defaults to 30 days, SameSite=Lax, Secure over HTTPS. It is not a login credential; it only proves "this client solved a PoW once".
  • The challenge page sends X-Robots-Tag: noindex, nofollow, Cache-Control: no-store and a strict CSP; it loads no external resources.
  • The signing key is derived from EasyAdmin:AesKey. Without it a per-process random key is used and a warning is logged; cookies die with the process.

7. Rate limiting and concurrency

  • Per IP: SlidingWindowRateLimiter, default 120 requests/minute, QueueLimit=0, immediate 429 with Retry-After. Windows are advanced on demand, so no timer per IP.
  • Global concurrency: GlobalConcurrencyLimit caps short requests entering the downstream pipeline, immediate 503 above it. Blazor circuits and SignalR long-lived connections are excluded, otherwise a handful of online users would consume the whole budget.
  • Static assets and /health are not rate limited; /api/ skips the challenge but is rate limited.

8. Path classes

Setting Default Meaning
ExemptPaths /health, /robots.txt, /sitemap.xml, /favicon.ico, /.well-known/, /api/ No challenge. Trailing / means prefix, otherwise exact. Configuring this replaces the default list
ExemptExtensions css/js/images/fonts/map/txt/xml/webmanifest Static extensions that skip the challenge
ProtectedPaths /_blazor, /hubs/ Require a cookie/login; 403 otherwise, never an HTML challenge

/api/ is deliberately challenge-free: mini programs, partner-signed APIs and payment/WeChat callbacks have no JS runtime. They rely on their own signatures, login state and rate limits; this extension still applies per-IP and global concurrency limits.

9. Deployment notes

  • The reverse proxy must forward the real IP. If local nginx does not set X-Forwarded-For, every request appears as loopback and ExemptLoopback=true lets everything through. Either overwrite X-Forwarded-For with $remote_addr, or set ExemptLoopback=false.
  • The extension relies on correctly configured ForwardedHeaders (KnownProxies / KnownNetworks); add cross-machine proxies to ForwardedProxies.
  • Configure EasyAdmin:AesKey in production (the host already validates it at startup); otherwise challenge cookies only live as long as the process.
  • Multi-instance: rate limiting, DNS cache and IP-range cache are per process; keep gateway-level limits as well.

10. Known limitations

  • A headless browser that executes JS can solve the PoW; this extension does not distinguish a human from an automated browser.
  • Distributed floods from a large IP pool can only be stopped at the edge plus the global concurrency cap; in-process per-IP limiting cannot do it alone.
  • A valid challenge cookie can be copied to another IP; it means "solved a PoW", not an identity.
  • If the official IP list cannot be fetched, the verifier falls back to double DNS (does not punish real crawlers), which is slightly weaker.

11. Verification

dotnet test EasyAdminBlazor.Tests --filter "FullyQualifiedName~BotGuardTests"

Covers PoW round-trip/tamper/expiry/malformed cookie, UA matching, double-DNS success/forward-mismatch/suffix lookalike, UserAgentOnly skipping DNS, same-name rule override, Bing JSON and plain-text CIDR parsing, and middleware behavior (challenge, static pass, /api/ pass, /_blazor 403 without cookie, signed-in pass, real crawler pass, fake crawler challenge, per-IP 429).

Runtime smoke (FMS with BotGuard__ExemptLoopback=false):

  • GET / with Accept: text/html → 200 challenge page with X-Robots-Tag: noindex;
  • GET /api/miniapp/tools → 200 JSON;
  • POST /_blazor/negotiate → 403;
  • 130 rapid requests → 117×200 + 13×429 (120 in the window);
  • solving with the same JS algorithm → GET / returns the real home page; flipping one character → challenged again;
  • /_blazor/negotiate with a valid cookie → 200.