How to implement IP whitelists in ASP.NET Core 6

When working with programs in ASP.Net Main 6, you will typically want to create an IP tackle whitelist to enable customer requests only from particular IP addresses, although blocking requests from all other addresses. We do this to protect our API endpoints from possibly destructive requests from poor actors, whilst at the very same time making it possible for requests originating from trustworthy IP addresses.

Also referred to as an IP safelist, an IP whitelist assists to guarantee that our application’s sensitive details is exposed only to IP addresses that we know and belief. An IP whitelist can be executed in ASP.Web Main by working with middleware or by working with MVC action filters. This write-up shows how we can apply an IP whitelist in ASP.Web Main 6 by using middleware.

To get the job done with the code examples delivered in this report, you really should have Visual Studio 2022 mounted in your process. If you do not already have a copy, you can obtain Visual Studio 2022 in this article.

Generate an ASP.Net Core Website API venture in Visible Studio 2022

Very first off, let’s develop an ASP.Net Core job in Visible Studio 2022. Pursuing these ways will develop a new ASP.Internet Core Web API task in Visual Studio 2022:

  1. Start the Visual Studio 2022 IDE.
  2. Simply click on “Create new job.”
  3. In the “Create new project” window, pick out “ASP.Web Core World wide web API” from the record of templates shown.
  4. Click Subsequent.
  5. In the “Configure your new project” window, specify the title and place for the new project.
  6. Optionally check out the “Place resolution and job in the very same directory” check box, depending on your tastes.
  7. Click Up coming.
  8. In the “Additional Information” window shown next, guarantee that the “Use controllers…” test box is checked. Depart the “Authentication Type” established to “None” (default). And make sure the test bins “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be utilizing any of those options right here.
  9. Click Generate.

We’ll use this ASP.Net Main 6 World wide web API challenge to perform with IP whitelists in the subsequent sections of this article.

The Method course in ASP.Web Main 6

System and Startup are the most important courses for configuring your .Net applications. On the other hand, ASP.Web Main 6 offers a simplified programming and hosting product that gets rid of most of the boilerplate code. You no lengthier have the Startup course now. As a substitute, you have to create your code to configure the request processing pipeline in the Method course.

When you build a new ASP.Net Main 6 job in Visible Studio, the Software course would glimpse like this:

var builder = WebApplication.CreateBuilder(args)
// Insert expert services to the container.
builder.Services.AddControllers()
var application = builder.Establish()
// Configure the HTTP request pipeline.
app.UseAuthorization()
app.MapControllers()
app.Operate()

We’ll use this Software course in the subsequent sections of this write-up. But to start with we’ll look at how we can implement an IP whitelist middleware in ASP.Internet Core 6.

Specify the whitelisted IP addresses in the config file

Specify the following whitelisted IP addresses in the appsettings.json file.

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

Be aware that these IP addresses have been specified for illustration functions only. You must switch these IP addresses with the IP addresses you would like to whitelist.

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

community course IPWhitelistOptions

   community List Whitelist get established

Develop the IPWhitelistMiddleware course

To create our middleware that will whitelist our IP addresses, develop a new class identified as IPWhitelistMiddleware with the subsequent code.

public class IPWhitelistMiddleware
    {
        personal readonly RequestDelegate _following
        non-public readonly IPWhitelistOptions _iPWhitelistOptions
        private readonly ILogger _logger
        community IPWhitelistMiddleware(RequestDelegate up coming,
        ILogger logger,
            IOptions applicationOptionsAccessor)
       
            _iPWhitelistOptions = applicationOptionsAccessor.Worth
            _subsequent = following
            _logger = logger
       
        general public async Undertaking Invoke(HttpContext context)
       
            if (context.Request.Technique != HttpMethod.Get.System)
           
                var ipAddress = context.Connection.RemoteIpAddress
                Checklist whiteListIPList =
                _iPWhitelistOptions.Whitelist
                var isIPWhitelisted = whiteListIPList
                .Where(ip => IPAddress.Parse(ip)
                .Equals(ipAddress))
                .Any()
                if (!isIPWhitelisted)
               
                    _logger.LogWarning(
                    "Ask for from Remote IP deal with: RemoteIp
                    is forbidden.", ipAddress)
                    context.Response.StatusCode =
                    (int)HttpStatusCode.Forbidden
                    return
               
                        
            await _next.Invoke(context)
       
    }

Be aware that, in this example, whitelisting of IP addresses will operate for all HTTP verbs except HTTP Get. If you want this whitelist to apply to all HTTP verbs, you can just remark out the adhering to statement in the Invoke method.

if (context.Request.Approach != HttpMethod.Get.System)

In the Invoke approach of our middleware, we’re looking through all whitelisted IP addresses in a Listing of string. If the IP deal with where the request originated matches a single of the IP addresses in the checklist, the request is permitted if not the middleware returns HTTP 403 Forbidden and a log information is created appropriately.

The IPWhitelistMiddlewareExtensions class

Now, develop a class named IPWhitelistMiddlewareExtensions and enter the next code.

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

We’ll use our IP whitelist middleware in the System class as illustrated in the upcoming segment.

Configure the IP whitelist middleware in the Method course

You ought to configure the IP whitelist middleware in the System class making use of the Configure approach of the Company selection, as revealed in the code snippet offered below.

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

Now, insert the following line of code in the System course to leverage the extension process we produced previously.

application.UseIPWhitelist()

Listed here is how your Program class should appear now:

employing IPWhiteListDemo
using Process.Configuration
var builder = WebApplication.CreateBuilder(args)
builder.Products and services.Configure(builder.Configuration.GetSection("IPWhitelistOptions"))
builder.Solutions.AddControllers()
var app = builder.Create()
app.UseIPWhitelist()
app.UseAuthorization()
application.MapControllers()
app.Run()

And lastly, run the application by urgent the F5 essential in Visual Studio. To examination the middleware, you can difficulty a HTTP Post request from Postman. If your IP deal with matches any of the IP addresses in the whitelist, the request will be allowed. Usually, the request will be denied and the middleware will return HTTP 403 Forbidden.

Copyright © 2022 IDG Communications, Inc.

diana

Next Post

W3BSTOCK to Host First-Ever Music Festival Powered by Blockchain Technology

Tue Jun 21 , 2022
W3BSTOCK, the initial-ever tunes festival run by blockchain technology, owned and organized by NFT holders, has introduced an event on June 20 at Manhattan’s Blue Creating. The night will aspect musical performances, art and an NFT gallery.  The W3BSTOCK party will contain stay songs from Brooklyn rapper DAP The Contract […]