How to Implement IP Whitelists in ASP.NET Core
By FoxLearn 2/3/2025 9:10:27 AM 105
This is often done through an IP whitelist (also known as an IP safelist), which ensures that only client requests from known, trusted IP addresses are allowed, while blocking requests from unauthorized or potentially malicious IP addresses.
In this guide, we’ll show you how to implement an IP whitelist in ASP.NET Core using middleware. This approach will allow you to filter requests based on their source IP and enforce restrictions where necessary.
Step 1: Specify Whitelisted IPs in the Configuration
Start by defining the list of IP addresses you wish to whitelist in your appsettings.json
file. These will be the trusted IPs that are allowed to make requests to your API.
{ "IPWhitelistOptions": { "Whitelist": [ "203.0.113.5", "198.51.100.10", "::1" ] } }
In this example, we've specified a few example IP addresses. Replace them with the actual IPs that should have access to your resources.
Next, create a configuration class that will hold these IP addresses:
public class IPWhitelistOptions { public List<string> Whitelist { get; set; } }
Step 2: Create the IPWhitelistMiddleware
Now, let’s build the middleware that will check if the incoming request's IP address is part of the whitelisted IPs. Create a new class called IPWhitelistMiddleware
:
public class IPWhitelistMiddleware { private readonly RequestDelegate _next; private readonly IPWhitelistOptions _ipWhitelistOptions; private readonly ILogger<IPWhitelistMiddleware> _logger; public IPWhitelistMiddleware(RequestDelegate next, ILogger<IPWhitelistMiddleware> logger, IOptions<IPWhitelistOptions> ipWhitelistOptions) { _next = next; _logger = logger; _ipWhitelistOptions = ipWhitelistOptions.Value; } public async Task InvokeAsync(HttpContext context) { var ipAddress = context.Connection.RemoteIpAddress?.ToString(); // Check if the IP is in the whitelist if (!_ipWhitelistOptions.Whitelist.Contains(ipAddress)) { _logger.LogWarning("Request from IP {IpAddress} is not allowed.", ipAddress); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; await context.Response.WriteAsync("Forbidden"); return; } await _next(context); } }
In this middleware, we check the incoming request's IP address against the list of whitelisted IPs. If the request is not from a trusted IP, we return a 403 Forbidden
response and log the event.
Step 3: Create Middleware Extensions
To make it easy to use the middleware in the Program.cs
file, we’ll add an extension method. Create a class called IPWhitelistMiddlewareExtensions
:
public static class IPWhitelistMiddlewareExtensions { public static IApplicationBuilder UseIPWhitelist(this IApplicationBuilder builder) { return builder.UseMiddleware<IPWhitelistMiddleware>(); } }
This extension method allows us to use the UseIPWhitelist
method to add the IP whitelist middleware to the request pipeline.
Step 4: Configure the Middleware in Program.cs
Now, let's configure the middleware in the Program.cs
file. We will need to configure the IP whitelist options to read from the appsettings.json
file, and then add our middleware to the pipeline.
Here's the updated Program.cs
:
var builder = WebApplication.CreateBuilder(args); // Load IP whitelist settings from the configuration builder.Services.Configure<IPWhitelistOptions>(builder.Configuration.GetSection("IPWhitelistOptions")); builder.Services.AddControllers(); var app = builder.Build(); // Use the IP whitelist middleware app.UseIPWhitelist(); app.UseAuthorization(); app.MapControllers(); app.Run();
Step 5: Testing the Middleware
Once your application is running, you can test it by sending a request from an IP that is either on the whitelist or not. Use a tool like Postman or curl to test:
- If your IP is whitelisted, the request will be allowed.
- If your IP is not whitelisted, you’ll receive a
403 Forbidden
response.
Customizing the Middleware for Specific HTTP Methods
If you want the whitelist to apply to specific HTTP methods (for example, POST or PUT), you can modify the InvokeAsync
method to filter by HTTP method. For example, to allow only POST
requests from whitelisted IPs, you can add the following check:
if (context.Request.Method != HttpMethod.Post.Method) { var ipAddress = context.Connection.RemoteIpAddress?.ToString(); if (!_ipWhitelistOptions.Whitelist.Contains(ipAddress)) { _logger.LogWarning("Request from IP {IpAddress} is not allowed.", ipAddress); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; await context.Response.WriteAsync("Forbidden"); return; } }
Implementing an IP whitelist in ASP.NET Core using middleware is a great way to secure your API or web application by limiting access to trusted IPs. With this approach, you can easily extend and customize the whitelist to fit your specific security needs.
- Options Pattern In ASP.NET Core
- Implementing Rate Limiting in .NET
- IExceptionFilter in .NET Core
- Repository Pattern in .NET Core
- CRUD with Dapper in ASP.NET Core
- How to Implement Mediator Pattern in .NET
- How to use AutoMapper in ASP.NET Core
- How to fix 'asp-controller and asp-action attributes not working in areas'