【新增】新增客户端IP限流模块。

This commit is contained in:
JianWeie
2022-05-20 14:48:06 +08:00
parent 05e2ff05bb
commit f973854d98
9 changed files with 228 additions and 1 deletions

View File

@@ -81,10 +81,14 @@ namespace CoreCms.Net.Configuration
#region Middleware中间件================================================================================
/// <summary>
/// Ip限流
/// 是否记录ip信息
/// </summary>
public static readonly bool MiddlewareIpLogEnabled = AppSettingsHelper.GetContent("Middleware", "IPLog", "Enabled").ObjToBool();
/// <summary>
/// 是否开启IP限流
/// </summary>
public static readonly bool MiddlewareIpRateLimitEnabled = AppSettingsHelper.GetContent("Middleware", "IpRateLimit", "Enabled").ObjToBool();
/// <summary>
/// 记录请求与返回数据
/// </summary>
public static readonly bool MiddlewareRequestResponseLogEnabled = AppSettingsHelper.GetContent("Middleware", "RequestResponseLog", "Enabled").ObjToBool();

View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AspNetCoreRateLimit;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CoreCms.Net.Core.Config
{
/// <summary>
/// IPLimit限流 启动服务
/// </summary>
public static class IpPolicyRateLimitSetup
{
public static void AddIpPolicyRateLimitSetup(this IServiceCollection services, IConfiguration Configuration)
{
if (services == null) throw new ArgumentNullException(nameof(services));
// 需要将限制规则存储到高速内存中
services.AddMemoryCache();
// 载入配置文件的规则设置
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
// 注入计数器和规则存储
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
// 注入计数器和规则分布式缓存存储(根据需求自行扩展)
//services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
//services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();
// 用于解析上下文的注入
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// 配置(解析器、计数器密钥生成器)
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
}
}
}

View File

@@ -11,6 +11,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AspNetCoreRateLimit" Version="4.0.2" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.2.0" />
<PackageReference Include="Autofac.Extras.DynamicProxy" Version="6.0.1" />
<PackageReference Include="Castle.Core" Version="4.4.1" />

View File

@@ -4,6 +4,10 @@
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AspNetCoreRateLimit" Version="4.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CoreCms.Net.Auth\CoreCms.Net.Auth.csproj" />
<ProjectReference Include="..\CoreCms.Net.Configuration\CoreCms.Net.Configuration.csproj" />

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AspNetCoreRateLimit;
using CoreCms.Net.Configuration;
using CoreCms.Net.Loging;
using Hangfire.Logging;
using Microsoft.AspNetCore.Builder;
using NLog;
using LogLevel = NLog.LogLevel;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 限制 ip 流量
/// </summary>
public static class IpLimitMiddleware
{
public static void UseIpLimitMiddle(this IApplicationBuilder app)
{
if (app == null) throw new ArgumentNullException(nameof(app));
try
{
if (AppSettingsConstVars.MiddlewareIpRateLimitEnabled)
{
app.UseIpRateLimiting();
}
}
catch (Exception e)
{
NLogUtil.WriteFileLog(LogLevel.Error, LogType.ApiRequest, "全局捕获异常", "限制ip流量异常", e);
throw;
}
}
}
}

View File

@@ -99,6 +99,8 @@ namespace CoreCms.Net.Web.Admin
services.AddHttpClient();
services.AddSingleton<WeChat.Service.HttpClients.IWeChatApiHttpClientFactory, WeChat.Service.HttpClients.WeChatApiHttpClientFactory>();
//<2F><><EFBFBD>ÿͻ<C3BF><CDBB><EFBFBD>IP<49><50><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
services.AddIpPolicyRateLimitSetup(Configuration);
//Swagger<65>ӿ<EFBFBD><D3BF>ĵ<EFBFBD>ע<EFBFBD><D7A2>
services.AddAdminSwaggerSetup();
@@ -171,6 +173,8 @@ namespace CoreCms.Net.Web.Admin
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// <20><><EFBFBD><EFBFBD>Ip<49><70><EFBFBD><EFBFBD>
app.UseIpLimitMiddle();
// <20><>¼<EFBFBD><C2BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EBB7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><><EFBFBD><E2BFAA>Ȩ<EFBFBD>ޣ<EFBFBD><DEA3><EFBFBD>Ȼ<EFBFBD><C8BB><EFBFBD><EFBFBD><EFBFBD>޷<EFBFBD>д<EFBFBD><D0B4>)
app.UseRequestResponseLog();
// <20>û<EFBFBD><C3BB><EFBFBD><EFBFBD>ʼ<EFBFBD>¼(<28><><EFBFBD><EFBFBD><EFBFBD>ŵ<EFBFBD><C5B5><EFBFBD><EFBFBD><EFBFBD><E3A3AC>Ȼ<EFBFBD><C8BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><ECB3A3><EFBFBD><EFBFBD><E1B1A8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD>ܷ<EFBFBD><DCB7><EFBFBD><EFBFBD><EFBFBD>)(ע<><EFBFBD><E2BFAA>Ȩ<EFBFBD>ޣ<EFBFBD><DEA3><EFBFBD>Ȼ<EFBFBD><C8BB><EFBFBD><EFBFBD><EFBFBD>޷<EFBFBD>д<EFBFBD><D0B4>)

View File

@@ -54,8 +54,73 @@
//记录IP请求数据
"IPLog": {
"Enabled": false
},
//开启Ip限流
"IpRateLimit": {
"Enabled": false
}
},
//ip限流规则设置
"IpRateLimiting": {
//如果EnableEndpointRateLimiting设置为false则限制将在全局范围内应用并且仅适用于端点的规则*。例如,如果您设置每秒 5 次调用的限制,则对任何端点的任何 HTTP 调用都将计入该限制。
//如果EnableEndpointRateLimiting设置为true则限制将适用于每个端点如{HTTP_Verb}{PATH}。例如,如果您为*:/api/values客户端设置每秒调用 5 次的限制则每秒可以调用GET /api/values5 次,但也可以调用 5 次PUT /api/values。
"EnableEndpointRateLimiting": false,
//如果StackBlockedRequests设置为false则拒绝的呼叫不会添加到节流计数器。如果客户端每秒发出 3 个请求并且您设置了每秒一个呼叫的限制则其他限制例如每分钟或每天计数器将仅记录第一个呼叫即未被阻止的呼叫。如果您希望被拒绝的请求计入其他限制您必须设置StackBlockedRequests为true.
"StackBlockedRequests": false,
//用于在您的RealIpHeaderKestrel 服务器位于反向代理之后时提取客户端 IP如果您的代理使用不同的标头则X-Real-IP使用此选项进行设置。
"RealIpHeader": "X-Real-IP",
//ClientIdHeader用于提取白名单的客户端 ID 。如果此标头中存在客户端 ID 并且与 ClientWhitelist 中指定的值匹配,则不应用速率限制。
"ClientIdHeader": "X-ClientId",
//IP白名单:支持Ip v4和v6如 //"IpWhitelist": [ "127.0.0.1", "::1/10", "192.168.0.0/24" ],
"IpWhitelist": [],
//端点白名单
"EndpointWhitelist": [ "get:/api/license", "*:/api/status" ],
//客户端白名单
"ClientWhitelist": [ "dev-client-1", "dev-client-2" ],
"QuotaExceededResponse": {
"Content": "{{\"status\":429,\"msg\":\"访问过于频繁,请稍后重试\",\"success\":false}}",
"ContentType": "application/json",
"StatusCode": 429
},
//返回状态码
"HttpStatusCode": 429,
//通用规则
//api规则,结尾一定要带*
"GeneralRules": [
//{
// //端点路径
// "Endpoint": "*:/api/*",
// //时间段,格式:{数字}{单位}可使用单位s, m, h, d
// "Period": "1m",
// //限制数量
// "Limit": 60
//},
//1秒钟只能调用3次
{
"Endpoint": "*",
"Period": "1s",
"Limit": 30
},
//1分钟只能调用300次
{
"Endpoint": "*",
"Period": "1m",
"Limit": 1000
},
//12H只能调用10000
{
"Endpoint": "*",
"Period": "12h",
"Limit": 100000
},
//7天只能调用100000次
{
"Endpoint": "*",
"Period": "7d",
"Limit": 1000000
}
]
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@@ -109,6 +109,8 @@ namespace CoreCms.Net.Web.WebApi
services.AddHttpClient();
services.AddSingleton<WeChat.Service.HttpClients.IWeChatApiHttpClientFactory, WeChat.Service.HttpClients.WeChatApiHttpClientFactory>();
//<2F><><EFBFBD>ÿͻ<C3BF><CDBB><EFBFBD>IP<49><50><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
services.AddIpPolicyRateLimitSetup(Configuration);
//Swagger<65>ӿ<EFBFBD><D3BF>ĵ<EFBFBD>ע<EFBFBD><D7A2>
services.AddClientSwaggerSetup();
@@ -178,6 +180,8 @@ namespace CoreCms.Net.Web.WebApi
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// <20><><EFBFBD><EFBFBD>Ip<49><70><EFBFBD><EFBFBD>
app.UseIpLimitMiddle();
// <20><>¼<EFBFBD><C2BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EBB7B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><><EFBFBD><E2BFAA>Ȩ<EFBFBD>ޣ<EFBFBD><DEA3><EFBFBD>Ȼ<EFBFBD><C8BB><EFBFBD><EFBFBD><EFBFBD>޷<EFBFBD>д<EFBFBD><D0B4>)
app.UseRequestResponseLog();
// <20>û<EFBFBD><C3BB><EFBFBD><EFBFBD>ʼ<EFBFBD>¼(<28><><EFBFBD><EFBFBD><EFBFBD>ŵ<EFBFBD><C5B5><EFBFBD><EFBFBD><EFBFBD><E3A3AC>Ȼ<EFBFBD><C8BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><ECB3A3><EFBFBD><EFBFBD><E1B1A8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD>ܷ<EFBFBD><DCB7><EFBFBD><EFBFBD><EFBFBD>)(ע<><EFBFBD><E2BFAA>Ȩ<EFBFBD>ޣ<EFBFBD><DEA3><EFBFBD>Ȼ<EFBFBD><C8BB><EFBFBD><EFBFBD><EFBFBD>޷<EFBFBD>д<EFBFBD><D0B4>)

View File

@@ -54,8 +54,73 @@
//记录IP请求数据
"IPLog": {
"Enabled": false
},
//开启Ip限流
"IpRateLimit": {
"Enabled": false
}
},
//ip限流规则设置
"IpRateLimiting": {
//如果EnableEndpointRateLimiting设置为false则限制将在全局范围内应用并且仅适用于端点的规则*。例如,如果您设置每秒 5 次调用的限制,则对任何端点的任何 HTTP 调用都将计入该限制。
//如果EnableEndpointRateLimiting设置为true则限制将适用于每个端点如{HTTP_Verb}{PATH}。例如,如果您为*:/api/values客户端设置每秒调用 5 次的限制则每秒可以调用GET /api/values5 次,但也可以调用 5 次PUT /api/values。
"EnableEndpointRateLimiting": false,
//如果StackBlockedRequests设置为false则拒绝的呼叫不会添加到节流计数器。如果客户端每秒发出 3 个请求并且您设置了每秒一个呼叫的限制则其他限制例如每分钟或每天计数器将仅记录第一个呼叫即未被阻止的呼叫。如果您希望被拒绝的请求计入其他限制您必须设置StackBlockedRequests为true.
"StackBlockedRequests": false,
//用于在您的RealIpHeaderKestrel 服务器位于反向代理之后时提取客户端 IP如果您的代理使用不同的标头则X-Real-IP使用此选项进行设置。
"RealIpHeader": "X-Real-IP",
//ClientIdHeader用于提取白名单的客户端 ID 。如果此标头中存在客户端 ID 并且与 ClientWhitelist 中指定的值匹配,则不应用速率限制。
"ClientIdHeader": "X-ClientId",
//IP白名单:支持Ip v4和v6如 //"IpWhitelist": [ "127.0.0.1", "::1/10", "192.168.0.0/24" ],
"IpWhitelist": [],
//端点白名单
"EndpointWhitelist": [ "get:/api/license", "*:/api/status" ],
//客户端白名单
"ClientWhitelist": [ "dev-client-1", "dev-client-2" ],
"QuotaExceededResponse": {
"Content": "{{\"status\":429,\"msg\":\"访问过于频繁,请稍后重试\",\"success\":false}}",
"ContentType": "application/json",
"StatusCode": 429
},
//返回状态码
"HttpStatusCode": 429,
//通用规则
//api规则,结尾一定要带*
"GeneralRules": [
//{
// //端点路径
// "Endpoint": "*:/api/*",
// //时间段,格式:{数字}{单位}可使用单位s, m, h, d
// "Period": "1m",
// //限制数量
// "Limit": 60
//},
//1秒钟只能调用3次
{
"Endpoint": "*",
"Period": "1s",
"Limit": 30
},
//1分钟只能调用300次
{
"Endpoint": "*",
"Period": "1m",
"Limit": 1000
},
//12H只能调用10000
{
"Endpoint": "*",
"Period": "12h",
"Limit": 100000
},
//7天只能调用100000次
{
"Endpoint": "*",
"Period": "7d",
"Limit": 1000000
}
]
},
"Logging": {
"LogLevel": {
"Default": "Information",