【发布时间】:2020-06-21 20:04:34
【问题描述】:
我想允许来自所有内部网站 (*.myintra.net) 以及所有 localhost 端口的 CORS 请求对一个公共内部 API 进行请求(当我们在 IIS Express 中本地调试各种应用程序时,即 http://localhost:12345, http://localhost:54321 等)。
This answer 向我展示了如何使用SetIsOriginAllowedToAllowWildcardSubdomains() 来允许所有子域。
This answer 向我展示了如何使用SetIsOriginAllowed() 委托函数来允许任何localhost 端口。
但是,这些选项似乎不能一起使用。我的配置:
private bool AllowLocalhost(string origin)
{
var uri = new Uri(origin);
return (uri.Host == "localhost");
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
string[] corsList = "https://*.myintra.net,https://some.specificurl.com".Split(",");
options.AddPolicy("CorsPolicy", builder =>
{
builder
.WithOrigins(corsList.ToArray())
.SetIsOriginAllowedToAllowWildcardSubdomains()
.SetIsOriginAllowed(origin => AllowLocalhost(origin)) // disallows calls from myapp.myintra.net since it doesn't uri.Host match "localhost"
...();
});
});
...
}
我可以交换配置的顺序:
.SetIsOriginAllowed(origin => AllowLocalhost(origin))
.SetIsOriginAllowedToAllowWildcardSubdomains()
但是AllowLocalhost() 函数永远不会被调用。我想一次只有一个工作是有道理的,因为第一次检查可能会返回true,而第二次检查可能会返回false。
理想情况下,我想要一个不需要我在 AllowLocalhost() 函数中重新实现 allow wildcard 逻辑的解决方案。
另外值得注意的是,我真的只需要在开发环境中使用它。生产需要允许通配符,但无论端口如何,都不允许使用localhost。
【问题讨论】:
-
支持
SetIsOriginAllowedToAllowWildcardSubdomains的逻辑是hidden behind aninternalextensions class,所以没有干净的方法可以得到它。 -
你有没有找到解决方案?
标签: c# asp.net-core cors asp.net-core-3.1