How to Restrict IP Address Using ASP.NET Core Web API

The below code is an way Restrict IP Address ASP.NET Core Web API IPFilter.cs Class



using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace API.CWCore
{
    public class IPFilter
    {
        private readonly RequestDelegate _next;
        private readonly ApplicationOptions _applicationOptions;
        public IPFilter(RequestDelegate next, IOptions applicationOptionsAccessor)
        {
            _next = next;
            _applicationOptions = applicationOptionsAccessor.Value;
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                var ipAddress = context.Connection.RemoteIpAddress;
                List whiteListIPList = _applicationOptions.Whitelist;
                var isInwhiteListIPList = whiteListIPList
                    .Where(a => IPAddress.Parse(a)
                    .Equals(ipAddress))
                    .Any();
                if (!isInwhiteListIPList)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    return;
                }
            }
            catch
            { }
            await _next.Invoke(context);
        }
    }
    public class ApplicationOptions
    {
        public List Whitelist { get; set; }
    }
    public static class MiddlewareExtensions
    {
        public static IApplicationBuilder UseIPFilter(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware();
        }
    }
}
And in Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;

namespace API.CWCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(Configuration.GetSection("ApplicationOptions"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
       
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseIPFilter();           
            app.UseMvc();
            app.UseStaticFiles();
        }
    }
}
Add "ApplicationOptions" into appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ApplicationOptions": {
    "Whitelist": [ "172.0.0.1", "::1", "114.199.71.208", "114.199.71.209", "14.241.247.248" ]
  },
  "AllowedHosts": "*",
  "CWCoreSetting": {
    "gwDalCore": "http://apbeta.6552455.info/dalcore/dal"
  }
}
Reactions

Post a Comment

0 Comments