这适用于我在 ASP Net Core 中:
我也有类似的问题。
在 startup.cs - ConfigureServices:
services.AddCors();
在 startup.cs - 配置:
// global cors policy
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
//.WithOrigins("https://localhost:44351")); // Allow only this origin can also have multiple origins separated with comma
.AllowCredentials()); // allow credentials
安装 NuGet 包: Microsoft.AspNetCore.Cors
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
现在可以使用 ex 从浏览器调用 api。 Javascript。
在这里找到:
https://jasonwatmore.com/post/2020/05/20/aspnet-core-api-allow-cors-requests-from-any-origin-and-with-credentials
示例 - 从 JS fetch api 访问:
在JS APP中:-获取api:
mode: 'cors',
credentials: 'include'
编辑:
我试图理解 CORS,这就是我现在的理解 - 如果我错了,请纠正我:
图片仅供参考,地址与文中不同。
CORS:
1.客户端请求从-https://localhost:5050获取网页
2.客户端获取网页
3. 客户端尝试使用 POST 或 GET 从 https://localhost:5050 获取 “GET” 数据一切都很好。
4.我们在https://localhost:6060 有一个API,我们希望将它与来自-https://localhost:5050 的网页一起使用
5. 客户端尝试从 API 获取 “GET” 数据 - https://localhost:6060
6. 客户端获取 CORS 错误消息 - 因为默认情况下,只有源“地址”https://localhost:6060 是唯一允许获取的、get、post等,像swagger等在同一个地址可以获取数据,但其他地址不能。但是没有服务器上的CORS配置,其他API怎么可能使用这个API。这是因为 CORS 与 browsers 及其停止响应的浏览器相关,因此在没有 CORS 的情况下将其与其他 API 一起使用没问题。
7.为了允许网页访问 API,它的服务器需要为此配置。
8. 服务器需要添加一个 Access-Control-Allow-Origin: https:/address:port 标头并返回允许的 Origin “地址”,即正在发送请求。
9. ASP net Core 在 Configure 方法中的startup.cs 中配置:
In ASP net Core is configured in the startup.cs in the Configure method:
// CORS - Allow calling the API from WebBrowsers
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
//.WithOrigins("https://localhost:44351")); // Allow only this origin can also have multiple origins seperated with comma
.SetIsOriginAllowed(origin => true));// Allow any origin
10. 这意味着当服务器返回响应时,它将添加 Access-Control-Allow-Origin: 与允许的来源地址。
11. 然后浏览器将获得 响应 并寻找 Access-Control-Allow-Origin:
如果有这个header并且值是发送请求“网页地址”的地址的origin强>。然后响应被 浏览器允许。
12. 如果没有 Access-Control-Allow-Origin: 标头,则表示服务器未配置 CORS,应在使用来自 浏览器 的 API 数据之前进行配置,其他 API 可以 GET 和 POST 数据,但客户端通过 浏览器不能。
13.如果响应中有Access-Control-Allow-Origin:标头但值不是当前地址,“web页面地址” 那么这意味着服务器没有为这个特定的网站配置。
结论:
因此,需要配置服务器才能使网站使用 API。这是默认的浏览器行为,如果 Access-Control-Allow-Origin: 标头不存在,浏览器将拒绝向客户端显示响应。如果 Access-Control-Allow-Origin: 存在但原始值与网站地址不同,浏览器将拒绝向客户端显示响应。这意味着在任何情况下,都应该使用 CORS configuration 配置服务器,以便客户端通过 Web 浏览器访问 API。其他 API 等可以从 API 获取数据,因为它们不是 Web 浏览器,并且没有 Web 浏览器 阻止 响应。
CORS 配置错误:
正如 @TwoFingerRightClick 所说,Allow All Origins 和 Allow Credentials 一起使用并不好。
为什么允许带有允许所有来源的凭据不太好。在帖子中,他们讨论了如果 CORS 像我在上面的代码中所做的那样错误配置,用户数据将如何被盗。我使用凭据并允许 CORS 的 misconfiguratin 的所有来源。所以 allow all origins 应该在没有 Allow 凭据的情况下使用。如果需要允许凭据,我们需要指定我们允许凭据的来源。所以我们需要使用注释行//.WithOrigins("https://localhost:44351")); // Allow only this origin can also have multiple origins separated with comma
允许凭据 - 允许带有请求和响应的 Cookie。
帖子: https://we45.com/blog/3-ways-to-exploit-cors-misconfiguration