7

I am using the standard ASP.NET Core middleware and I would like to allow IP address ranges (in my case, I am looking for the private IP address ranges), to ease development.

Currently, my middleware looks like this:

app.UseCors(builder =>
    builder.WithOrigins("http://localhost:8080", "https://test-env.com")
           .AllowAnyHeader()
           .AllowAnyMethod());

But now I would like to add a range of IPs, e.g. 172.16.0.0–172.31.255.255, in CIDR notation 172.16.0.0/12. How do I do it?

I tried the following and neither seems to work:

  • http://172.16.0.0/12:4200
  • http://172.16.*.*:4200
  • http://172.16.*:4200
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
eddyP23
  • 6,420
  • 7
  • 49
  • 87

1 Answers1

7

ASP.NET Core 2.0 introduced the ability to take full control over how an origin is validated, using the SetIsOriginAllowed method. Here's an example of how it might be configured:

app.UseCors(builder =>
    builder.SetIsOriginAllowed(MyIsOriginAllowed) 
           .AllowAnyHeader()
           .AllowAnyMethod());

// ...

private static bool MyIsOriginAllowed(string origin)
{
    var isAllowed = false;

    // Your logic.

    return isAllowed;
}

The callback passed into SetIsOriginAllowed is of type Func<string, bool> and is expected to return true for allowed origins and false otherwise.

In terms of validating against a range itself, there's another answer that might be helpful: How to see if an IP address belongs inside of a range of IPs using CIDR notation?.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203