Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core allow IP ranges in CORS

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
like image 928
eddyP23 Avatar asked Mar 28 '19 12:03

eddyP23


People also ask

How do I whitelist an IP address in NET Core?

An IP whitelist can be implemented in ASP.NET Core by using middleware or by using MVC action filters.

How do I allow all CORS in NET Core?

There are three ways to enable CORS: In middleware using a named policy or default policy. Using endpoint routing. With the [EnableCors] attribute.


1 Answers

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?.

like image 186
Kirk Larkin Avatar answered Oct 01 '22 04:10

Kirk Larkin