ResearchCave.Cloudflare (1.1.38)
Installation
dotnet nuget add source --name ResearchCave --username your_username --password your_token http://git.researchcave.com/api/packages/ResearchCave/nuget/index.jsondotnet add package --source ResearchCave --version 1.1.38 ResearchCave.CloudflareAbout this package
Trusted Cloudflare client IP and country resolution middleware for ASP.NET Core applications.
ResearchCave.Cloudflare
Trusted Cloudflare client IP and country resolution for ASP.NET Core.
The package only accepts Cloudflare headers when the immediate TCP peer is in Cloudflare's published IPv4 or IPv6 ranges. Requests arriving directly from other addresses have spoofable Cloudflare IP and country headers removed.
The CIDRs are stored as an embedded text resource. They are read and parsed once, on first use, into a thread-safe process-wide cache; request processing does not perform file or network I/O.
Install
dotnet add package ResearchCave.Cloudflare
Configure
Register the services and place the middleware early in the request pipeline, before authentication, rate limiting, logging, or application middleware that reads the client IP.
using ResearchCave.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResearchCaveCloudflare();
var app = builder.Build();
app.UseResearchCaveCloudflare();
app.UseAuthentication();
app.UseAuthorization();
The compatibility names AddCloudflareRealIpResolver() and UseCloudflareRealIpResolver() are also available.
After the middleware runs, HttpContext.Connection.RemoteIpAddress contains the trusted CF-Connecting-IP value for Cloudflare requests. For direct requests it remains the socket peer address.
Read request information
Inject ICloudflareRequestContext into request-scoped services or endpoints:
using ResearchCave.Cloudflare;
app.MapGet("/request-info", (ICloudflareRequestContext cloudflare) => new
{
cloudflare.IsFromCloudflare,
ClientIp = cloudflare.ClientIpAddress?.ToString(),
CloudflareProxyIp = cloudflare.ProxyIpAddress?.ToString(),
cloudflare.CountryCode
});
The country is read from Cloudflare's trusted CF-IPCountry header. Values such as XX (unknown) and T1 (Tor) are returned unchanged. It is null for direct requests or invalid headers.
You can also read the immutable request snapshot directly:
var info = httpContext.GetCloudflareRequestInfo();
var countryCode = httpContext.GetCloudflareCountryCode();
Security notes
- Run this middleware before any component that consumes the client IP or Cloudflare headers.
- Do not independently trust
CF-Connecting-IP,True-Client-IP, orCF-IPCountryelsewhere in the application. - Restrict the origin firewall to Cloudflare networks when the application must not be reachable directly.
- Update
cloudflare-ip-ranges.txtand release a new package when Cloudflare changes its published ranges.