JN.IpFilter
Simple IP Filter for ASP.NET Core.
Current version
Current version is 1.0.1
Release notes for current version
- Changed default return HTTP status code to Forbidden (403)
- Added override option to return HTTP status code
To do list
Some new features will be added to future releases.
Planned features
- Deny access based on list of invalid (not allowed) IP addresses
Install
Download the package from NuGet:
Install-Package JN.IpFilter -version [version number]
The package is available here and source code is available here.
Usage
Use the UseIpFilter extension method to add the middleware inside the Configure method on the Startup class. This should be done before others middlewares are added.
The UseIpFilter extension method needs a list of filters and an options object that can be read from configuration.
Example
The following code shows an example of the Configure method.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// (...)
var filters = Configuration.GetIpFilters("IpFilters");
var options = Configuration.GetIpFilterOptions("IpFilterMiddlewareOptions");
app.UseIpFilter(filters, options);
//(...)
}
Options
The filters and options can be read from configuration. The appsettings.json file could be something like the following.
The default HTTP status code is Forbidden (403). It can be overridden in the options object by specifiying a new code in ResponseHttpStatusCode field.
{
"IpFilterMiddlewareOptions": {
"ExactPathMatch": false,
"LogRequests": true,
"ApplyOnlyToHttpMethod": "",
"ResponseHttpStatusCode": 401
},
"IpFilters": [
{
"Path": "/MyController",
"IpList": "1.1.1.1;::1"
},
{
"Path": "/MyController2",
"IpList": "*"
},
{
"Path": "/MyController3",
"IpList": "2.2.2.2"
}
],
}
The available options are as follows:
- ExactPathMatch - if
false, then any filter whose path starts with the path being validated will be used to validate access. For example if path being validated is /MyController4 then filter with path /MyController can be used to validate the request IP. Iftrue, this behaviour is not allowed. - LogRequests - log requests using the ILogger provided
- ApplyOnlyToHttpMethod - apply filter to a specific Http method (POST, GET, ...)
- ResponseHttpStatusCode - HTTP status code to return - optional; if not specified Forbidden (403) will be used.