【问题标题】:Asp.Net Core allow IP ranges in CORSAsp.Net Core 允许 CORS 中的 IP 范围
【发布时间】:2019-08-19 06:01:44
【问题描述】:

我正在使用标准的 ASP.NET Core 中间件,并且我希望允许 IP 地址范围(在我的情况下,我正在寻找私有 IP 地址范围)以简化开发。

目前,我的中间件是这样的:

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

但现在我想添加一系列 IP,例如172.16.0.0–172.31.255.255,采用 CIDR 表示法 172.16.0.0/12。我该怎么做?

我尝试了以下方法,但似乎都不起作用:

  • http://172.16.0.0/12:4200
  • http://172.16.*.*:4200
  • http://172.16.*:4200

【问题讨论】:

  • 您的最终解决方案是什么?我很乐意允许所有给定的 IP 范围。

标签: c# asp.net-core cors


【解决方案1】:

ASP.NET Core 2.0 引入了使用 SetIsOriginAllowed 方法完全控制如何验证源的能力。这是一个如何配置的示例:

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

// ...

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

    // Your logic.

    return isAllowed;
}

传入SetIsOriginAllowed 的回调是Func<string, bool> 类型,对于允许的来源,预计返回true,否则返回false

就针对范围本身进行验证而言,还有另一个可能有用的答案:How to see if an IP address belongs inside of a range of IPs using CIDR notation?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2020-12-06
    • 2019-01-23
    • 2022-10-24
    • 2017-03-22
    • 2018-12-23
    • 2018-07-05
    相关资源
    最近更新 更多