C# 如何更新ASPNetCoreRateLimit lib的retry after值?
我有一个Asp.Net核心Web项目,并在中间件中实现了针对DOS和DDOS攻击的ASPNetCoreRateLimit包,如下所示。在“appsetting.json”文件中,IpRateLimiting设置是在中间件方法下配置的,如下所述。在IpRateLimiting设置中,如果请求计数在30分钟内超过1000,则显示并测试配额超出响应,一切正常。我想配置阻塞时间,我的意思是,如果请求计数超过appsettings.json中“GeneralRules”部分提到的限制,我想阻塞这个IP超过30分钟,正如“GeneralRules”部分再次提到的。默认情况下,如果请求计数超过“设置”中提到的值,则库会阻止IP,并且在此期间之后,阻止被禁用。如何以编程方式配置或覆盖blockin periondC# 如何更新ASPNetCoreRateLimit lib的retry after值?,c#,asp.net-core,rate-limiting,period,C#,Asp.net Core,Rate Limiting,Period,我有一个Asp.Net核心Web项目,并在中间件中实现了针对DOS和DDOS攻击的ASPNetCoreRateLimit包,如下所示。在“appsetting.json”文件中,IpRateLimiting设置是在中间件方法下配置的,如下所述。在IpRateLimiting设置中,如果请求计数在30分钟内超过1000,则显示并测试配额超出响应,一切正常。我想配置阻塞时间,我的意思是,如果请求计数超过appsettings.json中“GeneralRules”部分提到的限制,我想阻塞这个IP超过
public class RateLimitMiddleware : IpRateLimitMiddleware
{
private readonly ILogger<IpRateLimitMiddleware> _logger;
public RateLimitMiddleware(
RequestDelegate next, IOptions<IpRateLimitOptions> options, IRateLimitCounterStore counterStore, IIpPolicyStore policyStore, IRateLimitConfiguration config, ILogger<IpRateLimitMiddleware> logger
) : base(next, options, counterStore, policyStore, config, logger)
{
policyStore.SeedAsync();
_logger = logger;
}
//TODO : mail request details
public override Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitRule rule, string retryAfter)
{
var message = "Maximum request limit exceeded!";
_logger.LogWarning(message + ". Details : " + httpContext);
httpContext.Response.Headers["Retry-After"] = retryAfter;
httpContext.Response.StatusCode = 429;
httpContext.Response.ContentType = "application/json";
return SpecificPageMiddleware.ReturnIndexPage(httpContext);
}
}
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": true,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"IpWhitelist": [ "" ],
"EndpointWhitelist": [ "" ],
"QuotaExceededResponse": {
"Content": "<!DOCTYPE html><html lang=\"tr\"><head><meta charset=\"utf-8\" /><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><title>HATA</title><meta name=\"description\" content=\"\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /><link rel=\"canonical\" href=\"https://www.airclinic.com.tr\" /> <link rel=\"shortcut icon\" href=\"favicon.ico\" /></head><body style=\"background-image: url(../assets/media/error/bg6.jpg);\"><div><div><div><h1 style=\"margin-top: 12rem;\">Hata Kodu : 429</h1><p></p><p\">Maksimum istek limiti aşılmıştır! Lütfen daha sonra tekrar deneyiniz</p></div></div></div></body></html>",
"ContentType": "text/html",
"StatusCode": 429
},
"GeneralRules": [
{
"Endpoint": "*",
"Period": "30m",
"Limit": 1000
}
]
}
公共类RateLimitMiddleware:IpRateLimitMiddleware
{
专用只读ILogger\u记录器;
公共差饷租值(
RequestDelegate下一步、IOptions选项、IRateLimitCounterStore计数器存储、IIpPolicyStore策略存储、IRateLimitConfiguration配置、ILogger记录器
):base(下一个、选项、计数器存储、策略存储、配置、记录器)
{
policyStore.SeedAsync();
_记录器=记录器;
}
//TODO:邮件请求详细信息
公共重写任务ReturnQuoteExceededResponse(HttpContext HttpContext,RateLimitRule规则,字符串retryAfter)
{
var message=“超过最大请求限制!”;
_logger.LogWarning(消息+”。详细信息:“+httpContext);
httpContext.Response.Headers[“在”]=retryAfter之后重试;
httpContext.Response.StatusCode=429;
httpContext.Response.ContentType=“应用程序/json”;
returnspecificpagemiddleware.ReturnIndexPage(httpContext);
}
}
“IpRateLimiting”:{
“EnableEndpointRateLimiting”:真,
“StackBlockedRequests”:正确,
“RealIpHeader”:“X-Real-IP”,
“clienthdeader”:“X-ClientId”,
“HttpStatusCode”:429,
“IpWhitelist”:[“”],
“端点白名单”:[“”],
“QuotaExceededResponse”:{
“内容”:“HATA HATA Kodu:429
如何以编程方式配置或覆盖blockin periond
public class RateLimitMiddleware : IpRateLimitMiddleware
{
private readonly ILogger<IpRateLimitMiddleware> _logger;
public RateLimitMiddleware(
RequestDelegate next, IOptions<IpRateLimitOptions> options, IRateLimitCounterStore counterStore, IIpPolicyStore policyStore, IRateLimitConfiguration config, ILogger<IpRateLimitMiddleware> logger
) : base(next, options, counterStore, policyStore, config, logger)
{
policyStore.SeedAsync();
_logger = logger;
}
//TODO : mail request details
public override Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitRule rule, string retryAfter)
{
var message = "Maximum request limit exceeded!";
_logger.LogWarning(message + ". Details : " + httpContext);
httpContext.Response.Headers["Retry-After"] = retryAfter;
httpContext.Response.StatusCode = 429;
httpContext.Response.ContentType = "application/json";
return SpecificPageMiddleware.ReturnIndexPage(httpContext);
}
}
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": true,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"IpWhitelist": [ "" ],
"EndpointWhitelist": [ "" ],
"QuotaExceededResponse": {
"Content": "<!DOCTYPE html><html lang=\"tr\"><head><meta charset=\"utf-8\" /><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><title>HATA</title><meta name=\"description\" content=\"\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /><link rel=\"canonical\" href=\"https://www.airclinic.com.tr\" /> <link rel=\"shortcut icon\" href=\"favicon.ico\" /></head><body style=\"background-image: url(../assets/media/error/bg6.jpg);\"><div><div><div><h1 style=\"margin-top: 12rem;\">Hata Kodu : 429</h1><p></p><p\">Maksimum istek limiti aşılmıştır! Lütfen daha sonra tekrar deneyiniz</p></div></div></div></body></html>",
"ContentType": "text/html",
"StatusCode": 429
},
"GeneralRules": [
{
"Endpoint": "*",
"Period": "30m",
"Limit": 1000
}
]
}
您可以访问控制器内的Ip策略存储,并按如下方式修改Ip规则:
public class RateLimitMiddleware : IpRateLimitMiddleware
{
private readonly ILogger<IpRateLimitMiddleware> _logger;
private readonly IpRateLimitOptions _options;
private readonly IIpPolicyStore _ipPolicyStore;
public RateLimitMiddleware(
RequestDelegate next, IOptions<IpRateLimitOptions> options, IRateLimitCounterStore counterStore, IIpPolicyStore policyStore, IRateLimitConfiguration config, ILogger<IpRateLimitMiddleware> logger
) : base(next, options, counterStore, policyStore, config, logger)
{
policyStore.SeedAsync();
_logger = logger;
_options = options.Value;
_ipPolicyStore = policyStore;
}
//TODO : mail request details
public override Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitRule rule, string retryAfter)
{
var message = "Maximum request limit exceeded!";
_logger.LogWarning(message + ". Details : " + httpContext);
httpContext.Response.Headers["Retry-After"] = retryAfter;
httpContext.Response.StatusCode = 429;
httpContext.Response.ContentType = "application/json";
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
var pol = _ipPolicyStore.Get(_options.IpPolicyPrefix);
pol.IpRules.Add(new IpRateLimitPolicy
{
Ip = ip,
Rules = new List<RateLimitRule>(new RateLimitRule[] {
rule
})
});
_ipPolicyStore.Set(_options.IpPolicyPrefix, pol);
return SpecificPageMiddleware.ReturnIndexPage(httpContext);
}
}
公共类RateLimitMiddleware:IpRateLimitMiddleware
{
专用只读ILogger\u记录器;
私有只读IpRateLimitOptions\u选项;
私人只读ipPolicyStore _ipPolicyStore;
公共差饷租值(
RequestDelegate下一步、IOptions选项、IRateLimitCounterStore计数器存储、IIpPolicyStore策略存储、IRateLimitConfiguration配置、ILogger记录器
):base(下一个、选项、计数器存储、策略存储、配置、记录器)
{
policyStore.SeedAsync();
_记录器=记录器;
_选项=选项.值;
_ipPolicyStore=保单存储;
}
//TODO:邮件请求详细信息
公共重写任务ReturnQuoteExceededResponse(HttpContext HttpContext,RateLimitRule规则,字符串retryAfter)
{
var message=“超过最大请求限制!”;
_logger.LogWarning(消息+”。详细信息:“+httpContext);
httpContext.Response.Headers[“在”]=retryAfter之后重试;
httpContext.Response.StatusCode=429;
httpContext.Response.ContentType=“应用程序/json”;
字符串ip=HttpContext.Current.Request.ServerVariables[“HTTP_X_FORWARDED_FOR”];
if(string.IsNullOrEmpty(ip))
{
ip=HttpContext.Current.Request.ServerVariables[“REMOTE_ADDR”];
}
var pol=_ipPolicyStore.Get(_options.IpPolicyPrefix);
pol.IpRules.Add(新的IpRateLimitPolicy
{
Ip=Ip,
规则=新列表(新RateLimitRule[]{
规则
})
});
_ipPolicyStore.Set(_options.IpPolicyPrefix,pol);
returnspecificpagemiddleware.ReturnIndexPage(httpContext);
}
}
Hi Michael,谢谢你的回答。你的逻辑非常完美,而且由于框架核心的原因,我更新了相同的代码,以获得远程Ip地址“var Ip=httpContext.Request.httpContext.Connection.RemoteIpAddress.ToString();”。不管怎样,它已经过测试并且可以工作。我可以在运行时为特定的远程Ip地址添加新规则