如何在asp.net core 3.1中为每种类型的请求启用Cors

yog*_*ing 5 c# cors asp.net-core asp.net-core-3.0 asp.net-core-3.1

如何为asp.net core 3.1中的每种类型的请求启用Cors?

我正在关注MS Docs,但它们似乎不起作用。

注意:我可以为特定域实现 cors,但不能为每个域实现。例如,我已将以下配置应用于我的项目:

  1. ConfigureServices();我添加的方法中:

    services.AddCors();

  2. Configure()我添加的方法中:

    app.UseCors(builder => { builder .WithOrigins() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); });

但是当我尝试从另一个 url 使用 jQuery 访问 API 时,我得到:

从源“ https://localhost:44361 ”访问“ https://localhost: 44314/Reservation”处的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“访问控制” -Allow-Origin'标头存在于请求的资源上。

现在,如果我将 URL 放入 WithOrigins() 方法中,我就可以访问 API:

app.UseCors(builder =>
{
    builder
    .WithOrigins("https://localhost:44361")
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials();
});
Run Code Online (Sandbox Code Playgroud)

我的问题是如何不受限制地向每个 URL(即域、子域等)授予对 API 的访问权限。应用 * 不起作用。

请帮忙。

Kev*_*vin 4

您需要允许您执行以下操作的任何来源:

builder.AllowAnyOrigin()

具有AllowCredentials 的任何来源

不允许从任何来源发送凭据是设计使然。

可以使用以下方法来解决这个问题

builder.SetIsOriginAllowed(_ => true)

我认为这不是一个很好的解决方案,因为它消除了 useCredentials() 的好处。

笔记

useCredentials在标头中发送 JWT 不需要。用于如果您需要在请求中发送cookie。允许任何来源并启用useCredentials可能会导致安全漏洞,这就是默认情况下不允许的原因。

欲了解更多信息,您应该阅读

Access-Control-Allow-Credentials 标头到底有什么作用?

CORS:当凭据标志为 true 时,无法在 Access-Control-Allow-Origin 中使用通配符