Piton.IPRestrictions.Endpoints.Telemetry 1.0.3

dotnet add package Piton.IPRestrictions.Endpoints.Telemetry --version 1.0.3
                    
NuGet\Install-Package Piton.IPRestrictions.Endpoints.Telemetry -Version 1.0.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Piton.IPRestrictions.Endpoints.Telemetry" Version="1.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Piton.IPRestrictions.Endpoints.Telemetry" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="Piton.IPRestrictions.Endpoints.Telemetry" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Piton.IPRestrictions.Endpoints.Telemetry --version 1.0.3
                    
#r "nuget: Piton.IPRestrictions.Endpoints.Telemetry, 1.0.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Piton.IPRestrictions.Endpoints.Telemetry@1.0.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Piton.IPRestrictions.Endpoints.Telemetry&version=1.0.3
                    
Install as a Cake Addin
#tool nuget:?package=Piton.IPRestrictions.Endpoints.Telemetry&version=1.0.3
                    
Install as a Cake Tool

ASP.Net Core IP restrictions

CI Piton.IPRestrictions.Endpoints Piton.IPRestrictions.Endpoints.Telemetry

Restricts endpoints to a list of addresses and networks. Opt in per endpoint, either with [RestrictIP] or .RestrictIP() on an endpoint convention builder, optionally with a predicate deciding per request whether the restriction applies.

Installation

Install the Piton.IPRestrictions.Endpoints NuGet package: dotnet add package Piton.IPRestrictions.Endpoints

<Project>
  <ItemGroup>
    <PackageReference Include="Piton.IPRestrictions.Endpoints" Version="..." />
  </ItemGroup>
</Project>

Usage

Configure in Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add the middleware services
builder.Services.AddIPRestrictions(o => 
{
    // Values can be either IP addresses or CIDR networks.
    o.AllowedIPs.Add("8.8.8.8");
    o.AllowedIPs.Add("198.51.100.0/24");
    
    o.AllowLANIPs = false; // Allow LAN addresses, default is false
});

app.Services.Configure<ForwardedHeadersOptions>(o =>
{
    // When behind a reverse proxy forwarded headers must be enabled, 
    // otherwise the remote address will always be the proxy's address.
    // See section Forwarded Headers below
    o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    o.ConfigureForReverseProxy(ReverseProxy.YourProxy);
    o.AddKnownNetworkForCurrentEnvironment();
});

// ... other services

var app = builder.Build();

app.UseForwardedHeaders();

// ... other middleware

app.UseRouting();

// The middleware must be added after UseRouting. Any middleware added before UseIPRestrictions 
// (e.g. authentication and authorization) runs first, even for requests it then denies.
app.UseIPRestrictions();

app.UseAuthentication();

// ... other middleware

Endpoints

Configuration is per endpoint, either with an attribute or a convention:

// Entire Controller
[RestrictIP]
public class Controller1 : ControllerBase
{
    public IActionResult Get() => Ok();
}

public class Controller2 : ControllerBase
{
    // Individual action
    [RestrictIP]
    public IActionResult Get() => Ok();
}

// Minimal API
app.MapGet("/minimal", () => "Hello, world!").RestrictIP();

// All controllers
app.MapControllers().RestrictIP();

// With a predicate: only applies the restriction if the predicate is matched
app.MapControllers().RestrictIP(context => context.Request.Method != HttpMethods.Get);

Mode

IPRestrictionsOptions.Mode is a combination of flags:

Flag Effect
Enabled Applies the IP restrictions. The default.
AddEndpointHeader Adds the client IP address to every response, in the RemoteEndpointHeaderName header.
Disabled Turns the middleware off entirely (no restrictions and no header), whatever else is set.

To enable the restrictions and add the header, set Mode to Enabled | AddEndpointHeader. To disable the middleware entirely, set Mode to Disabled.

Configuration

AddIPRestrictions() binds the options from the IPRestrictions configuration section (or another section, given as an argument), and follows configuration reloads, so for example appsettings.json:

{
  "IPRestrictions": {
    "Mode": "Enabled, AddEndpointHeader",
    "AllowedIPs": [
      "8.8.8.8",
      "198.51.100.0/24",
      "2001:db8::/32"
    ],
    "AllowLanIPs": false,
    "AllowLoopbackIPs": true
  }
}

Forwarded Headers

There are two things to be aware of when using this library behind a reverse proxy:

  • Many reverse proxies (like Nginx, Cloudflare and Envoy) append (not override) the original client IP address to the X-Forwarded-For header, allowing a client to spoof their IP address by adding a fake X-Forwarded-For header.
  • Since .NET 8, forwarded headers are only applied for known proxies. If your reverse proxy is not in the list of known proxies, the forwarded headers middleware will not apply the forwarded headers.

To help with this, the library contains two helper functions:

  • ConfigureForReverseProxy - configures the forwarded headers options for a specific reverse proxy (see Reverse Proxies below)
  • AddKnownNetworkForCurrentEnvironment - adds the correct value to ForwardedHeadersOptions.KnownIPNetworks for certain known environments (see Known Environments below).
app.UseForwardedHeaders(new ForwardedHeadersOptions()
    { ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor }
    .ConfigureForReverseProxy(ReverseProxy.YourProxy) // Configure for the specific reverse proxy you are using
    .AddKnownNetworkForCurrentEnvironment(); // Adds the correct value to ForwardedHeadersOptions.KnownIPNetworks for the current environment

Logging

By default the middleware logs allowed and denied requests (at Debug) under the Microsoft.AspNetCore.IPRestrictions category, like ASP.NET Core's own middleware, so the usual "Microsoft.AspNetCore": "Warning" logging configuration applies to it too. To log under the middleware's own category (Piton.IPRestrictions.Endpoints.IPRestrictionsMiddleware), set IPRestrictionsOptions.UseMicrosoftLoggingNamespace to false.

Configuration problems (such as an invalid entry in AllowedIPs) are always logged at Warning under Piton.IPRestrictions.Endpoints.IPRestrictionsOptions.

Metrics

The middleware records metrics with System.Diagnostics.Metrics, on the Piton.IPRestrictions meter (IPRestrictionsMetrics.MeterName). Each is a counter of requests to endpoints with IP restrictions, in {request}, enabled by an option in IPRestrictionsOptions.Metrics:

Instrument Counts Option Default
piton.ip_restrictions.requests All requests, including ones the endpoint's predicate exempted TotalRequests Off
piton.ip_restrictions.allowed_requests Allowed requests AllowedRequests Off
piton.ip_restrictions.denied_requests Denied requests DeniedRequests On

To export them with OpenTelemetry, install the Piton.IPRestrictions.Endpoints.Telemetry package:

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics => metrics.AddIPRestrictionsInstrumentation());

or manually without the package:

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics => metrics.AddMeter(IPRestrictionsMetrics.MeterName));
Configure metrics

To leave requests out of the metrics, set Filter, which is called with the same endpoint, client IP address and whether the request was denied, and returns whether to record the request.

To add tags to the metrics, set ConfigureTags, which is called with a reference to the tag list, the same endpoint, client IP address and whether the request was denied.

builder.Services.AddIPRestrictions(o =>
{
    // Exclude permitted health checks from all metrics
    o.Metrics.Filter = (endpoint, remoteIp, denied) => !denied && endpoint?.DisplayName != "Health checks";
    
    // Tag api vs non-api endpoints
    o.Metrics.ConfigureTags = (ref TagList tags, endpoint, remoteIp, denied) =>
        tags.Add("api", endpoint is RouteEndpoint { RoutePattern.RawText: { } route } && route.StartsWith("/api") ? "true" : "false");
});

Each distinct combination of tag values is a separate time series, so tags should have a low cardinality (few distinct values) to avoid high memory usage and performance issues.

AddIPRestrictionsInstrumentation can also configure the metrics options:

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics => metrics.AddIPRestrictionsInstrumentation(o =>
    {
        // Configure metrics options here
    }));

Reverse Proxies

Parsing X-Forwarded-For is a security risk since many reverse proxies (like Cloudflare and Envoy) append (not override) the original client IP address to the client-supplied X-Forwarded-For header, allowing a client to spoof their IP address by adding a fake X-Forwarded-For header. However, reverse proxies also commonly put the actual client IP in a different header. This library includes a function ConfigureForReverseProxy that configures the correct header value for the known proxies below.

Reverse Proxy Header Notes
Envoy X-Envoy-External-Address Envoy only sets this header when use_remote_address is true (i.e. it is the edge proxy). Used by Azure Container Apps (see Envoy HTTP Headers)
Cloudflare CF-Connecting-IP See Cloudflare HTTP Headers
Traefik X-Real-IP See Traefik HTTP Headers
YARP X-Forwarded-For By default YARP removes any incoming X-Forwarded-For headers (see YARP Forwarded Headers)
Caddy X-Forwarded-For By default Caddy ignores incoming X-Forwarded-* values unless the request comes from one of its trusted_proxies (see Caddy reverse_proxy defaults)
Azure Front Door X-Azure-SocketIP See Azure Front Door HTTP Headers

Known Environments

Since .NET 8, forwarded headers are only applied when the request comes from a known proxy (see ForwardedHeadersOptions.KnownIPNetworks). This library includes a helper function AddKnownNetworkForCurrentEnvironment that adds the correct value to ForwardedHeadersOptions.KnownIPNetworks for certain known environments, detected by an environment variable:

Environment Environment Variable Known IP Networks Notes
Azure Container Apps CONTAINER_APP_REPLICA_NAME 100.64.0.0/10 The default RFC 6598 CG-NAT network. An environment in a custom virtual network may use a different network.
Azure App Service WEBSITE_SITE_NAME 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 Documented for the App Service load balancer. Added both as IPv4 and IPv4-mapped IPv6 networks.
Kubernetes KUBERNETES_SERVICE_HOST 10.0.0.0/8 The pod network depends on the cluster's configuration, so this may need to be changed.
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.3 95 11/11/2026
1.0.2 81 11/10/2026
1.0.1 79 11/10/2026