如何在 asp.net core 3.1 中为每种类型的请求启用 Cors?
我正在关注 MS Docs但它们似乎不起作用。
注意:我能够为特定域实现 cors,但不能为每个域实现。例如,我已将以下配置应用于我的项目:
在
ConfigureServices();
方法中我添加了:services.AddCors();
在
Configure()
方法中我添加了:app.UseCors( builder => { build 者 .WithOrigins() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); });
但是当我尝试从另一个 url 使用 jQuery 访问 API 时,我得到:
Access to XMLHttpRequest at 'https://localhost:44314/Reservation' from origin 'https://localhost:44361' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
现在,如果我将 URL 放入 WithOrigins() 方法中,我就可以访问 API:
app.UseCors(builder =>
{
builder
.WithOrigins("https://localhost:44361")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
我的问题是如何让每个 URL(即域、子域等)不受限制地访问 API。应用 * 不起作用。
请帮忙。
最佳答案
您需要允许您使用以下方式执行的任何来源:
builder.AllowAnyOrigin()
具有 AllowCredentials 的任何来源
不允许从任何来源发送凭据是设计使然。
您可以通过使用以下方法解决这个问题
builder.SetIsOriginAllowed(_ => true)
我认为这不是一个很好的解决方案,因为它消除了 useCredentials() 的好处。
注意
在 header 中发送 JWT 不需要useCredentials
。它用于是否需要在请求中发送 cookie。允许任何来源并启用 useCredentials
会导致安全漏洞,这就是默认情况下不允许的原因。
有关更多信息,您应该阅读
What exactly does the Access-Control-Allow-Credentials header do?
和
CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
关于c# - 如何在 asp.net core 3.1 中为每种类型的请求启用 Cors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60636051/