Mar 11 2024
{
"AllowedIPs": [
"192.168.1.1",
"127.0.0.1"
// Add more IPs as needed
]
}
public class IPWhitelistMiddleware
{
private readonly RequestDelegate _next;
private readonly IConfiguration _configuration;
public IPWhitelistMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_configuration = configuration;
}
public async Task InvokeAsync(HttpContext context)
{
var remoteIp = context.Connection.RemoteIpAddress;
var allowedIPs = _configuration.GetSection("AllowedIPs").Get<string[]>();
if (!IPAddress.IsLoopback(remoteIp) && !allowedIPs.Contains(remoteIp?.ToString()))
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Access denied");
return;
}
await _next(context);
}
}
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseMiddleware<IPWhitelistMiddleware>(); // Register the IP Whitelist middleware
app.UseAuthorization();
app.MapControllers();
app.Run();
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.