Search code examples
c#asp.net-corecorsasp.net-core-webapiip-address

How to allow CORS with IP address in ASP.NET Core Web API project?


I am using the ASP.NET Core Web API project I want to allow CORS policy with someone's IP address and I would like to allow IP address ranges. Using this CORS method this is allow CORS for everyone I want to allow only one IP address. Can anyone help me?

This is my method to allow CORS for everyone in my Program.cs file.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Add CORS support
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

// Enable CORS
app.UseCors();

app.MapControllers();

app.Run();

Solution

  • You can use SetIsOriginAllowed to implement it.

    builder.Services.AddCors(options =>
    {
        options.AddDefaultPolicy(policyBuilder =>
        {
            policyBuilder.SetIsOriginAllowed(origin =>
            {
                // Convert domain to IP 
                // be careful, domains can have multiple IPs
                var host = new Uri(origin).Host;
                var ipAddresses = Dns.GetHostAddresses(host);
    
                // List of allowed IPs
                var allowedIPs = new List<IPAddress>
                {
                    IPAddress.Parse("192.168.1.1"), // Replace with your allowed IPs
                    IPAddress.Parse("192.168.1.2")  // Another IP
                };
    
                return ipAddresses.Any(ip => allowedIPs.Contains(ip));
            })
            .AllowAnyMethod()
            .AllowAnyHeader();
        });
    });