When working with functions in ASP.NET Core 6, you’ll typically wish to create an IP deal with whitelist to permit consumer requests solely from sure IP addresses, whereas blocking requests from all different addresses. We do that to guard our API endpoints from probably malicious requests from dangerous actors, whereas on the identical time permitting requests originating from trusted IP addresses.
Additionally referred to as an IP safelist, an IP whitelist helps to make sure that our software’s delicate information is uncovered solely to IP addresses that we all know and belief. An IP whitelist could be applied in ASP.NET Core by utilizing middleware or by utilizing MVC motion filters. This text exhibits how we are able to implement an IP whitelist in ASP.NET Core 6 by utilizing middleware.
To work with the code examples supplied on this article, it’s best to have Visible Studio 2022 put in in your system. When you don’t have already got a duplicate, you’ll be able to obtain Visible Studio 2022 right here.
Create an ASP.NET Core Internet API venture in Visible Studio 2022
First off, let’s create an ASP.NET Core venture in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core Internet API venture in Visible Studio 2022:
- Launch the Visible Studio 2022 IDE.
- Click on on “Create new venture.”
- Within the “Create new venture” window, choose “ASP.NET Core Internet API” from the record of templates displayed.
- Click on Subsequent.
- Within the “Configure your new venture” window, specify the title and site for the brand new venture.
- Optionally examine the “Place resolution and venture in the identical listing” examine field, relying in your preferences.
- Click on Subsequent.
- Within the “Extra Data” window proven subsequent, make sure that the “Use controllers…” examine field is checked. Depart the “Authentication Kind” set to “None” (default). And ensure the examine bins “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we gained’t be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core 6 Internet API venture to work with IP whitelists within the subsequent sections of this text.
The Program class in ASP.NET Core 6
Program and Startup are the primary courses for configuring your .NET functions. Nevertheless, ASP.NET Core 6 offers a simplified programming and internet hosting mannequin that removes a lot of the boilerplate code. You now not have the Startup class now. As an alternative, it’s a must to write your code to configure the request processing pipeline within the Program class.
Once you create a brand new ASP.NET Core 6 venture in Visible Studio, the Program class would appear like this:
var builder = WebApplication.CreateBuilder(args);
// Add providers to the container.
builder.Providers.AddControllers();
var app = builder.Construct();
// Configure the HTTP request pipeline.
app.UseAuthorization();
app.MapControllers();
app.Run();
We’ll use this Program class within the subsequent sections of this text. However first we’ll study how we are able to implement an IP whitelist middleware in ASP.NET Core 6.
Specify the whitelisted IP addresses within the config file
Specify the next whitelisted IP addresses within the appsettings.json file.
"IPWhitelistOptions": {
"Whitelist": [ "192.168.0.9", "192.168.1.9", "::1" ]
}
Word that these IP addresses have been given for illustration functions solely. You must change these IP addresses with the IP addresses you wish to whitelist.
Now create a brand new class named IPWhitelistOptions with the next code, which is able to learn the config values (IP addresses) we simply specified.
public class IPWhitelistOptions
{
public Listing<string> Whitelist { get; set; }
}
Create the IPWhitelistMiddleware class
To construct our middleware that may whitelist our IP addresses, create a brand new class referred to as IPWhitelistMiddleware with the next code.
public class IPWhitelistMiddleware
{
personal readonly RequestDelegate _next;
personal readonly IPWhitelistOptions _iPWhitelistOptions;
personal readonly ILogger<IPWhitelistMiddleware> _logger;
public IPWhitelistMiddleware(RequestDelegate subsequent,
ILogger<IPWhitelistMiddleware> logger,
IOptions<IPWhitelistOptions> applicationOptionsAccessor)
{
_iPWhitelistOptions = applicationOptionsAccessor.Worth;
_next = subsequent;
_logger = logger;
}
public async Job Invoke(HttpContext context)
{
if (context.Request.Methodology != HttpMethod.Get.Methodology)
{
var ipAddress = context.Connection.RemoteIpAddress;
Listing<string> whiteListIPList =
_iPWhitelistOptions.Whitelist;
var isIPWhitelisted = whiteListIPList
.The place(ip => IPAddress.Parse(ip)
.Equals(ipAddress))
.Any();
if (!isIPWhitelisted)
{
_logger.LogWarning(
"Request from Distant IP deal with: {RemoteIp}
is forbidden.", ipAddress);
context.Response.StatusCode =
(int)HttpStatusCode.Forbidden;
return;
}
}
await _next.Invoke(context);
}
}
Word that, on this instance, whitelisting of IP addresses will work for all HTTP verbs besides HTTP Get. If you’d like this whitelist to use to all HTTP verbs, you’ll be able to simply remark out the next assertion within the Invoke technique.
if (context.Request.Methodology != HttpMethod.Get.Methodology)
Within the Invoke technique of our middleware, we’re studying all whitelisted IP addresses in a Listing of string. If the IP deal with the place the request originated matches one of many IP addresses within the record, the request is allowed; in any other case the middleware returns HTTP 403 Forbidden and a log message is generated accordingly.
The IPWhitelistMiddlewareExtensions class
Now, create a category named IPWhitelistMiddlewareExtensions and enter the next code.
public static class IPWhitelistMiddlewareExtensions
{
public static IApplicationBuilder UseIPWhitelist(this
IApplicationBuilder builder)
{
return builder.UseMiddleware<IPWhitelistMiddleware>();
}
}
We’ll use our IP whitelist middleware within the Program class as illustrated within the subsequent part.
Configure the IP whitelist middleware within the Program class
You must configure the IP whitelist middleware within the Program class utilizing the Configure technique of the Service assortment, as proven within the code snippet given under.
builder.Providers.Configure<IPWhitelistOptions>(builder.Configuration.GetSection("IPWhitelistOptions"));
Now, insert the next line of code within the Program class to leverage the extension technique we created earlier.
app.UseIPWhitelist();
Right here is how your Program class ought to look now:
utilizing IPWhiteListDemo;
utilizing System.Configuration;
var builder = WebApplication.CreateBuilder(args);
builder.Providers.Configure<IPWhitelistOptions>(builder.Configuration.GetSection("IPWhitelistOptions"));
builder.Providers.AddControllers();
var app = builder.Construct();
app.UseIPWhitelist();
app.UseAuthorization();
app.MapControllers();
app.Run();
Lastly, run the applying by urgent the F5 key in Visible Studio. To check the middleware, you’ll be able to challenge a HTTP Put up request from Postman. In case your IP deal with matches any of the IP addresses within the whitelist, the request shall be allowed. In any other case, the request shall be denied and the middleware will return HTTP 403 Forbidden.
Copyright © 2022 IDG Communications, Inc.