【问题标题】:React-call to "Asp.Net Core with identity server" gives CORS-errors对“带有身份服务器的 Asp.Net Core”的反应调用给出了 CORS 错误
【发布时间】:2021-04-12 08:09:28
【问题描述】:

我会尽量保持简短以拯救数字雨林。请询问我是否遗漏了任何细节。

我在 VS 中有一个“asp .net 3.1 core + react”项目模板,内置身份服务器。这工作正常,但我现在想在一个单独的项目中做我的反应项目。所以我开始了一个新的 create-react-app-project。

所以,从我的新反应项目中,当我调用 OidcConfigurationController 时。调用控制器方法,我可以单步执行服务器端的代码。然后我收到一个客户端错误“无法获取”,这似乎表明了 CORS 错误。

这是我在 chrome dev 工具栏->network 中检查标题时得到的结果

Request URL: https://localhost:5001/authentication/_configuration/MyProject.Web
Referrer Policy: strict-origin-when-cross-origin
:authority: localhost:5001
:method: GET
:path: /authentication/_configuration/MyProject.Web
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,sv;q=0.8
origin: http://localhost:3000
referer: http://localhost:3000/
sec-ch-ua: "Google Chrome";v="87", " Not;A Brand";v="99", "Chromium";v="87"
sec-ch-ua-mobile: ?0
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36

这些是 startup.cs 中的相关行

ConfigureServices()

services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                        builder =>
                        {
                            //builder.WithOrigins("http://localhost:3002/", "https://localhost:3001")
                            builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                        });
});

services.AddSingleton<ICorsPolicyService>((container) => {
    var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
    return new DefaultCorsPolicyService(logger)
    {
        AllowAll = true
    };
});

配置()

app.UseCors(MyAllowSpecificOrigins); // I also tried to switch order on these 2 rows
app.UseIdentityServer();

我在这里所做的一切似乎都没有改变标题中的推荐人策略,仍然得到完全相同的消息

React 调用只是一个简单的 fetch(address-of-the-controller-that-it-hits)。

我还尝试启动一个新的服务器端项目(asp net core api)并设置相同的 CORS 策略,我可以从我的 react 客户端调用此 api 而不会出现任何错误)

【问题讨论】:

  • 你能告诉我们你在开发工具中的错误信息吗?根据您的描述,我找不到任何错误。

标签: reactjs asp.net-core identityserver4


【解决方案1】:

因此,在请求中,您会看到 origin: http://localhost:3000 标头被使用。这是 CORS 请求的来源。但是请求是针对这个 URL 的:

https://localhost:5001/authentication/_configuration/MyProject.Web

难道不是从不安全的 HTTP 到 HTTPS 的重定向存在干扰吗?

请确保您也在 IdentityServer 中设置了 CORS 设置。

有关详细信息,请参阅CORS 文档。

作为旁注,IIS 也可能导致 CORS 问题,有关详细信息,请参阅此答案:

IIS hijacks CORS Preflight OPTIONS request

【讨论】:

  • 嗨撕!感谢您的回复!我会检查这个并在“正常”工作后回复
  • 我还会发布来自 Fiddler (telerik.com/download/fiddler) 的失败请求的副本,这样更容易查明那里有什么问题。
猜你喜欢
  • 1970-01-01
  • 2019-05-25
  • 2021-08-05
  • 2021-08-05
  • 2020-05-07
  • 2017-07-26
  • 2019-07-11
  • 2019-09-24
  • 2021-06-01
相关资源
最近更新 更多