达到速率限制时出现 CORS 错误而不是预期的 429 响应



在我的后端,我在我的.net核心实体框架后端中使用AspNetCoreRateLimit包实现了IpRateLimit中间件。当 IP 地址 x 在特定时间进行 y 次调用时,它会被阻止一段时间,后端应返回 429 错误,这在使用邮递员测试时工作正常。但是当我使用 axios 发出请求时,由于 ip 速率限制器,应该被阻止,我收到一个 axios 错误:

"Access to XMLHttpRequest at 'https://localhost:44372/api/Users/Login/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
"POST https://localhost:44372/api/Users/Login/ net::ERR_FAILED"

收到此错误后,我添加了所需的标头,但它没有更改结果。对我的后端的其他 axios 请求(也发布、放置和删除)工作正常,但是当 ip 速率限制器命中时,我只是收到 cors 错误。

我在应用程序中实现了限制器,如以下教程所示: https://edi.wang/post/2019/6/16/ip-rate-limit-for-aspnet-core

反应公理请求:

async function buildPostAndFetch(url, param, header) {
const finalurl = `${BASE_URL}${url}`;
return axios.post(finalurl, param, {headers:{"Access-Control-Allow-Origin": "*"}})
.then(res => {
response(res);
return res.data ? res.data : true;
})
.catch(err => {              
handleError(err);
return false;
})        
}
handleError() {
const handleError = err => {
setError(true);

if(err.request?.status === 0) {
console.log("*********************************************")
console.log(err.request);
console.log("*********************************************")
// throw new Error("API is currently offline or you are not connected to the internet:(");
} else if(err.response.status === 429) {
console.log("*********************************************")
console.log(err.response);
console.log("*********************************************")
}
}
}

当重新提问和限制器命中时,我总是进入err.request.status === 0路径。

默认情况下,大多数服务器系统/运行时不会将应用程序集标头添加到4xx5xx响应中,而只会将它们添加到2xx成功响应中,并可能添加到3xx重定向中。

因此,您可能需要执行显式配置以强制标头添加到 4xx 响应中,以便该429响应以Access-Control-Allow-Origin标头结束。

例如,在Apache和nginx中,这是通过将always关键字添加到header-set指令来完成的。也许你的服务器系统有一些类似的东西。

您会收到 CORS 错误,因为该429错误没有Access-Control-Allow-Origin标头。

首先,确保你具有来自 NuGet 的Install-Package Microsoft.AspNetCore.Cors

然后,请将以下内容添加到您的Startup.cs

public void ConfigureServices(IServiceCollection services)
{
// Put it before AddMvc() if there's any
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Put it before UseMvc() if there's any
app.UseCors(
options => options
.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
);
app.UseMvc();
}

完成上述配置后,通过检查网络选项卡(浏览器的开发人员工具),您可能会看到返回的响应标头之一为access-control-allow-origin : http://localhost:3000

尝试:

app.UseCors(opt => opt
.WithOrigins("http://localhost:3000"")
.AllowAnyHeader()
.AllowAnyMethod());

协议(http/https)不能省略。此外,cors 中间件应放置在app.UseRouting之后但在UseAuthorization之前。

你可以看到中间件顺序。

最新更新