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
- Generic: every public deployment has this problem; it is not business-specific.
- Ordering: it must run after
UseForwardedHeadersto see the real client IP and afterUseAuthenticationto let signed-in users through. - The framework's
EasyAdminAuthStartupFilteris anIStartupFilter; middleware it adds runs before everyapp.Use...in the host'sProgram.cs, andClientIpResolveronly readsConnection.RemoteIpAddress. It therefore cannot be auto-mounted there — the host callsUseEasyAdminBlazorBotGuard()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
Enabled=false→ pass through.- Loopback address and
ExemptLoopback=true→ pass (local debugging, health checks). OPTIONS→ pass.- Non-static / non-health path → per-IP rate limit, otherwise 429.
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).- Signed-in user (
ExemptAuthenticated) or a valid challenge cookie → pass. ExemptPaths(default/health,/robots.txt,/sitemap.xml,/favicon.ico,/.well-known/,/api/) and static assets → pass.- UA matches a configured crawler rule → verify according to the configured strength; pass on success, continue on failure.
- Anonymous
GET/HEADwithAcceptcontainingtext/htmlor*/*→ return the challenge page. - 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|difficultywith HMAC; the cookie isticket.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.
ChallengeDifficultyis 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,Secureover 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-storeand 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 withRetry-After. Windows are advanced on demand, so no timer per IP. - Global concurrency:
GlobalConcurrencyLimitcaps 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
/healthare 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 andExemptLoopback=truelets everything through. Either overwriteX-Forwarded-Forwith$remote_addr, or setExemptLoopback=false. - The extension relies on correctly configured
ForwardedHeaders(KnownProxies/KnownNetworks); add cross-machine proxies toForwardedProxies. - Configure
EasyAdmin:AesKeyin 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 /withAccept: text/html→ 200 challenge page withX-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/negotiatewith a valid cookie → 200.