ASP.NET Core如何限制请求频率,为了防止恶意请求,我们往往会对接口请求的频率做限制,比如请求间隔,一段时间内请求的次数,针对部分IP做出不同的限制策略
如何去限制请求频率不需要我们去实现,用上AspNetCoreRateLimit 轮子就好了????
Github地址:https://github.com/stefanprodan/AspNetCoreRateLimit
Nuget下载
Install-Package AspNetCoreRateLimit
第一步自然是修改Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// 需要从appsettings.json中加载配置
services.AddOptions();
// 存储IP计数器及配置规则
services.AddMemoryCache();
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
// 按照文档,这两个是3.x版的breaking change,要加上
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
}
//以及
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// 注意顺序,放在 UseMvc 上面
app.UseIpRateLimiting();
app.UseMvc();
}
然后向appsettings.json加入限制配置
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"GeneralRules": [
{
"Endpoint": "*:/Home/*?",
"Period": "1m",
"Limit": 3
}
]
}
EnableEndpointRateLimiting设置为true,意思是IP限制会应用于单个配置的Endpoint上。如果是false的话,只会限制所有 * 的规则,而不能达到针对单个Endpoint配置的目的。
HttpStatusCode设置为429,意思是触发限制之后给客户端返回的HTTP状态码。
GeneralRules里我只配置了一条,针对/Home这URL的限制。其中,开头的 *: 表示任何HTTP VERB,如GET/POST,而结尾的 /* 表示需要考虑/Home后面的参数,也就是我MVC Action参数里的route参数。它不会匹配
Home也不会匹配Home/*/*
如果您在appsettings.json配置文件中定义了静态费率策略,则需要在应用程序启动时为它们添加种子:
public static async Task Main(string[] args)
{
IWebHost webHost = CreateWebHostBuilder(args).Build();
using (var scope = webHost.Services.CreateScope())
{
// get the IpPolicyStore instance
var ipPolicyStore = scope.ServiceProvider.GetRequiredService<IIpPolicyStore>();
// seed IP data from appsettings
await ipPolicyStore.SeedAsync();
}
await webHost.RunAsync();
}
当请求接口超过限制时!!!会出现以下错误
轮子还提供动态更新限制策略!!!
通过注入IOptions<IpRateLimitOptions> 和IIpPolicyStore可以实时更新限制策略
public class SpiderController : BlogControllerBase
{
private readonly IpRateLimitOptions _options;
private readonly IIpPolicyStore _ipPolicyStore;
public SpiderController(IOptions<IpRateLimitOptions> optionsAccessor
, IIpPolicyStore ipPolicyStore)
{
_options = optionsAccessor.Value;
_ipPolicyStore = ipPolicyStore;
}
public async Task<IActionResult> Index(SpiderSelectCondition spiderSelect)
{
var pol = await _ipPolicyStore.GetAsync(_options.IpPolicyPrefix);
pol.IpRules.Add(new IpRateLimitPolicy
{
Ip = "",
Rules = new List<RateLimitRule>(new RateLimitRule[] {
new RateLimitRule {
Endpoint = "*:/Spider/Config",
Limit = 2,
PeriodTimespan=new TimeSpan(0,0,10),
Period ="1d"}
})
});
await _ipPolicyStore.SetAsync(_options.IpPolicyPrefix, pol);
return View();
}
PeriodTimespan 为间隔时间
Period 一定时间内可执行Limit次
更多高级用法可以访问官方文档