Damian Bod made a blog post demonstrating how to implement middleware for managing a list of IP addresses.
It provides examples of global middleware or an action filter.
In any case, you need to add the allowed IP addresses to your appsettings.json
and check the client IP address on them.
The client IP is accessible through an HttpContext
(e.g. context.Connection.RemoteIpAddress
).
If you want to use the IP address range whitelist, you can use the Nuget IPAddressRange package, which supports various formats such as “192.168.0.0/24” and “192.168.0.0/255.255.255.0", including CIDR and IPv6 expressions.
Here is an example of how to do this in a filter:
appsettings.json
{ "IPAddressWhitelistConfiguration": { "AuthorizedIPAddresses": [ "::1", // IPv6 localhost "127.0.0.1", // IPv4 localhost "192.168.0.0/16", // Local network "10.0.0.0/16", // Local network ] } }
IPWhiteListConfiguration.cs
namespace My.Web.Configuration { using System.Collections.Generic; public class IPWhitelistConfiguration : IIPWhitelistConfiguration { public IEnumerable<string> AuthorizedIPAddresses { get; set; } } }
Startup.cs
public class Startup {
ClientIPAddressFilterAttribute.cs
namespace My.Web.Filters { using System.Collections.Generic; using System.Linq; using System.Net; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using NetTools; using My.Web.Configuration; public class ClientIPAddressFilterAttribute : ActionFilterAttribute { private readonly IEnumerable<IPAddressRange> authorizedRanges; public ClientIPAddressFilterAttribute(IIPWhitelistConfiguration configuration) { this.authorizedRanges = configuration.AuthorizedIPAddresses .Select(item => IPAddressRange.Parse(item)); } public override void OnActionExecuting(ActionExecutingContext context) { var clientIPAddress = context.HttpContext.Connection.RemoteIpAddress; if (!this.authorizedRanges.Any(range => range.Contains(clientIPAddress))) { context.Result = new UnauthorizedResult(); } } }
source share