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
An IP whitelist can be implemented in ASP.NET Core by using middleware or by using MVC action filters.
There are three ways to enable CORS: In middleware using a named policy or default policy. Using endpoint routing. With the [EnableCors] attribute.
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With