February 3, 2023

Mulvihill-technology

For computer aficionados

How to implement IP whitelists in ASP.NET Core 6

When doing work with programs in ASP.Net Core 6, you will typically want to produce an IP handle whitelist to allow client requests only from specified IP addresses, while blocking requests from all other addresses. We do this to shield our API endpoints from likely malicious requests from undesirable actors, whilst at the similar time letting requests originating from dependable IP addresses.

Also called an IP safelist, an IP whitelist allows to guarantee that our application’s sensitive information is exposed only to IP addresses that we know and believe in. An IP whitelist can be executed in ASP.Net Main by employing middleware or by utilizing MVC motion filters. This article reveals how we can put into practice an IP whitelist in ASP.Net Main 6 by utilizing middleware.

To work with the code illustrations provided in this posting, you ought to have Visible Studio 2022 set up in your procedure. If you never presently have a copy, you can down load Visual Studio 2022 here.

Produce an ASP.Net Main Web API challenge in Visible Studio 2022

Initial off, let us make an ASP.Net Core challenge in Visual Studio 2022. Pursuing these steps will develop a new ASP.Internet Core Website API venture in Visible Studio 2022:

  1. Start the Visible Studio 2022 IDE.
  2. Click on “Create new job.”
  3. In the “Create new project” window, select “ASP.Web Core World wide web API” from the checklist of templates exhibited.
  4. Click Subsequent.
  5. In the “Configure your new project” window, specify the name and place for the new undertaking.
  6. Optionally verify the “Place option and task in the same directory” check out box, dependent on your preferences.
  7. Simply click Future.
  8. In the “Additional Information” window demonstrated subsequent, assure that the “Use controllers…” examine box is checked. Depart the “Authentication Type” set to “None” (default). And make absolutely sure the check packing containers “Enable Docker,” “Configure for HTTPS,” and “Enable Open up API Support” are unchecked as we won’t be applying any of those options here.
  9. Click on Create.

We’ll use this ASP.Web Core 6 Internet API challenge to do the job with IP whitelists in the subsequent sections of this report.

The Application class in ASP.Web Main 6

Application and Startup are the primary classes for configuring your .Web programs. Even so, ASP.Internet Core 6 presents a simplified programming and hosting model that eliminates most of the boilerplate code. You no lengthier have the Startup course now. Instead, you have to publish your code to configure the request processing pipeline in the System class.

When you produce a new ASP.Net Core 6 project in Visual Studio, the Application course would glance like this:

var builder = WebApplication.CreateBuilder(args)
// Incorporate services to the container.
builder.Products and services.AddControllers()
var app = builder.Establish()
// Configure the HTTP ask for pipeline.
app.UseAuthorization()
application.MapControllers()
application.Operate()

We’ll use this System course in the subsequent sections of this posting. But initially we’ll study how we can employ an IP whitelist middleware in ASP.Net Main 6.

Specify the whitelisted IP addresses in the config file

Specify the adhering to whitelisted IP addresses in the appsettings.json file.

"IPWhitelistOptions": 
    "Whitelist": [ "192.168.0.9", "192.168.1.9", "::1" ]
 

Note that these IP addresses have been supplied for illustration uses only. You really should substitute these IP addresses with the IP addresses you would like to whitelist.

Now produce a new course named IPWhitelistOptions with the next code, which will go through the config values (IP addresses) we just specified.

public class IPWhitelistOptions

   general public Record Whitelist get established

Make the IPWhitelistMiddleware class

To construct our middleware that will whitelist our IP addresses, produce a new course termed IPWhitelistMiddleware with the pursuing code.

public course IPWhitelistMiddleware
    {
        personal readonly RequestDelegate _up coming
        personal readonly IPWhitelistOptions _iPWhitelistOptions
        private readonly ILogger _logger
        general public IPWhitelistMiddleware(RequestDelegate upcoming,
        ILogger logger,
            IOptions applicationOptionsAccessor)
       
            _iPWhitelistOptions = applicationOptionsAccessor.Worth
            _upcoming = future
            _logger = logger
       
        general public async Job Invoke(HttpContext context)
       
            if (context.Ask for.Method != HttpMethod.Get.Method)
           
                var ipAddress = context.Connection.RemoteIpAddress
                Record whiteListIPList =
                _iPWhitelistOptions.Whitelist
                var isIPWhitelisted = whiteListIPList
                .In which(ip => IPAddress.Parse(ip)
                .Equals(ipAddress))
                .Any()
                if (!isIPWhitelisted)
               
                    _logger.LogWarning(
                    "Ask for from Distant IP deal with: RemoteIp
                    is forbidden.", ipAddress)
                    context.Response.StatusCode =
                    (int)HttpStatusCode.Forbidden
                    return
               
                        
            await _upcoming.Invoke(context)
       
    }

Observe that, in this example, whitelisting of IP addresses will function for all HTTP verbs except HTTP Get. If you want this whitelist to use to all HTTP verbs, you can just comment out the adhering to assertion in the Invoke technique.

if (context.Ask for.System != HttpMethod.Get.System)

In the Invoke process of our middleware, we’re looking through all whitelisted IP addresses in a List of string. If the IP handle the place the ask for originated matches 1 of the IP addresses in the listing, the ask for is allowed or else the middleware returns HTTP 403 Forbidden and a log concept is produced accordingly.

The IPWhitelistMiddlewareExtensions course

Now, generate a class named IPWhitelistMiddlewareExtensions and enter the pursuing code.

 public static class IPWhitelistMiddlewareExtensions
   
        community static IApplicationBuilder UseIPWhitelist(this
        IApplicationBuilder builder)
       
            return builder.UseMiddleware()
       
   

We’ll use our IP whitelist middleware in the System course as illustrated in the future portion.

Configure the IP whitelist middleware in the Software class

You must configure the IP whitelist middleware in the Method course using the Configure approach of the Service assortment, as shown in the code snippet provided below.

builder.Companies.Configure(builder.Configuration.GetSection("IPWhitelistOptions"))

Now, insert the following line of code in the Program course to leverage the extension system we created previously.

application.UseIPWhitelist()

Here is how your Plan course really should appear now:

using IPWhiteListDemo
employing System.Configuration
var builder = WebApplication.CreateBuilder(args)
builder.Providers.Configure(builder.Configuration.GetSection("IPWhitelistOptions"))
builder.Providers.AddControllers()
var app = builder.Build()
app.UseIPWhitelist()
application.UseAuthorization()
app.MapControllers()
application.Operate()

And finally, operate the software by urgent the F5 crucial in Visual Studio. To test the middleware, you can issue a HTTP Write-up ask for from Postman. If your IP address matches any of the IP addresses in the whitelist, the ask for will be permitted. If not, the request will be denied and the middleware will return HTTP 403 Forbidden.

Copyright © 2022 IDG Communications, Inc.