Secure Your API By IP Whitelisting Using ASP.NET Core 8 Web API
In today’s digital landscape, securing APIs is a top priority, especially when exposing services over the internet. One way to increase security is through IP whitelisting — a technique that restricts access to only a specified set of IP addresses, effectively blocking traffic from unauthorized sources. This can be a crucial component in applications where access must be tightly controlled, like in financial services, internal APIs, or administrative dashboards.
In this blog, we’ll dive deep into how to implement IP whitelisting in an ASP.NET Core 8 Web API using a custom middleware.
What is IP Whitelisting?
IP Whitelisting is the process of allowing access to a web service only from pre-approved IP addresses. This ensures that even if someone has the correct credentials, they cannot access the API unless they’re using an approved IP address.
In an ASP.NET Core Web API, this functionality can be implemented via middleware that intercepts incoming requests, checks the origin’s IP, and determines whether to grant or deny access based on the whitelist.
Setting up IP Whitelisting in ASP.NET Core 8
Step 1: Creating the Middleware
Middleware is perfect for this task since it can inspect each HTTP request as it arrives. The following code shows how to create a custom IPWhitelistMiddleware
that checks the client’s IP address against a predefined whitelist in the configuration:
using System.Net;
namespace BEArgentina.Services.AuthAPI.Middlewares
{
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)
{
// Get the remote IP address of the client
var remoteIp = context.Connection.RemoteIpAddress;
// Fetch the allowed IPs from configuration
var allowedIPs = _configuration.GetSection("AllowedIPs").Get<string[]>();
// Check if the remote IP is in the allowed IP list
if (!IPAddress.IsLoopback(remoteIp) && !allowedIPs.Contains(remoteIp?.ToString()))
{
// If the IP is not allowed, return a forbidden response
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync($"Access denied from IP: {remoteIp}");
return;
}
// Proceed to the next middleware in the pipeline if the IP is allowed
await _next(context);
}
}
}
Step 2: Registering Middleware in Program.cs
Now that the middleware is created, we need to register it in the request pipeline. Open your Program.cs
file and add the IPWhitelistMiddleware
to the pipeline using app.UseMiddleware
.
Here’s how to do that:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Configure IP whitelist middleware
var app = builder.Build();
// Adding IP Whitelisting Middleware
app.UseMiddleware<BEArgentina.Services.AuthAPI.Middlewares.IPWhitelistMiddleware>();
// Configure the HTTP request pipeline.
app.MapControllers();
app.Run();
Step 3: Configuring Allowed IPs in appsettings.json
We’ll store the list of allowed IP addresses in the appsettings.json
file. This makes it easy to configure and update the whitelist without touching the application’s codebase.
Add the following section to your appsettings.json
:
{
"AllowedIPs": [
"192.168.1.100",
"203.0.113.42",
"203.0.113.50"
]
}
In this example, the application will only allow requests originating from the IP addresses 192.168.1.100
, 203.0.113.42
, and 203.0.113.50
.
Step 4: Testing the Middleware
Now that you’ve set up the middleware and configured the allowed IPs, you can test the functionality by sending requests from an unauthorized IP. The middleware should respond with:
Access denied from IP: {client IP}
If the IP address is allowed, the request will proceed as usual.
Enhancing IP Whitelisting
You can enhance the basic implementation of IP whitelisting in several ways, such as:
-
Environment-Specific IP Whitelists: You may want different whitelists for different environments (development, staging, production). This can be handled by creating environment-specific configuration files (
appsettings.Development.json
,appsettings.Production.json
). -
CIDR Support: Instead of only allowing individual IP addresses, you could allow entire IP ranges using CIDR notation. This would require checking if the client’s IP falls within the allowed range.
-
Dynamic IP Whitelisting: You could build a more dynamic system by fetching the allowed IPs from a database or a remote API, allowing administrators to update the whitelist without restarting the application.
Real-World Use Cases
IP whitelisting can be useful in various scenarios:
-
Internal APIs: APIs that are only intended for internal use, such as those used by company applications or within corporate networks.
-
Administrative Panels: Admin panels or dashboards that should only be accessible from within the office network or through a VPN.
-
Compliance Requirements: Some industries, such as finance or healthcare, have strict compliance requirements that mandate restricting access based on IP address.
-
External Service Access: APIs that allow access to external services but want to limit access to specific trusted partners or clients.
Conclusion
Implementing IP whitelisting in an ASP.NET Core 8 Web API adds an additional layer of security to your application. By controlling which IP addresses can access your API, you mitigate the risk of unauthorized access, especially to sensitive or administrative endpoints.
This simple yet effective technique can be easily set up using middleware in ASP.NET Core. You can also customize and enhance the whitelist logic as needed to fit more complex scenarios or requirements.
By implementing this security measure, your APIs are much more robust and ready to handle real-world security challenges.
Praful's Newsletter 🚀
Join 3900+ Engineers to Level Up Your Skills!
Subscribe to my Software Engineering Deep Dive Series covering ReactJS, Redux, ASP.NET Core, and Clean Architecture. Get 1 insightful email each week to enhance your development journey.