Once you have added the IpSecuritySettings.cs, you will need to configure the options in the Startup.cs. Add the IpSecuritySettings in ConfigureServices with the Configure extension method:
publicclassStartup{publicStartup(IHostingEnvironment env) {var builder =newConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional:false, reloadOnChange:true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:true) .AddEnvironmentVariables(); Configuration =builder.Build(); }publicIConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.publicvoidConfigureServices(IServiceCollection services) { // Adds services required for using options.services.AddOptions(); // Register the IConfiguration instanceservices.AddSingleton<IConfiguration>(Configuration); // Configure settingsservices.Configure<IpSecuritySettings>(Configuration.GetSection("IpSecuritySettings")); // Add framework services.services.AddMvc(); }}
Setup the middleware
Add a new file IpRestrictionMiddleware.cs to filtering the request which is not whitelisted IP addresses:
publicclassIpRestrictionMiddleware{publicreadonlyRequestDelegate Next;publicreadonlyILogger<IpRestrictionMiddleware> Logger;publicreadonlyIpSecuritySettings IpSecuritySettings; public IpRestrictionMiddleware(RequestDelegate next, ILogger<IpRestrictionMiddleware> logger, IOptions<IpSecuritySettings> ipSecuritySettings)
{ Next = next; Logger = logger; IpSecuritySettings =ipSecuritySettings.Value; }publicasyncTaskInvoke(HttpContext context) {var ipAddress = (string)context.Connection.RemoteIpAddress?.ToString();if (!IpSecuritySettings.AllowedIPsList.Contains(ipAddress)) {context.Response.StatusCode=403;Logger.LogInformation($"Forbidden Request from Remote IP address: {ipAddress}");return; }awaitNext(context); }}
In the Startup.cs, add IpRestrictionMiddleware as the middleware in the pipeline in Configure with the UseMiddleware extension method:
publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory){loggerFactory.AddConsole(Configuration.GetSection("Logging"));loggerFactory.AddDebug(); // Enable IP Restriction Middlewareapp.UseMiddleware<IpRestrictionMiddleware>();app.UseMvc();}