Asp.Net Core allow IP ranges in CORS

岁酱吖の 提交于 2020-01-21 05:14:47

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/55398058/asp-net-core-allow-ip-ranges-in-cors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!