我正在使用标准的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
答案 0 :(得分:2)
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?。