From 0a2ba8bb1a1b54fc7ed106763ae9139e0e638d09 Mon Sep 17 00:00:00 2001 From: lq1405 <2769838458@qq.com> Date: Tue, 8 Apr 2025 21:02:12 +0800 Subject: [PATCH] =?UTF-8?q?V=201.0.8=20=E6=B7=BB=E5=8A=A0=20=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E5=85=AC=E9=92=A5=20=E7=99=BB=E5=BD=95=20=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=E7=9A=84IP=E9=99=90=E9=80=9F=20=E6=AF=8F=E5=88=86?= =?UTF-8?q?=E9=92=9F=E4=BA=94=E6=AC=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LMS.service/LMS.service.csproj | 1 + LMS.service/Program.cs | 18 ++++++++++++++++++ LMS.service/appsettings.json | 29 ++++++++++++++++++++++++++++- 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/LMS.service/LMS.service.csproj b/LMS.service/LMS.service.csproj index b8ef9a2..4708f52 100644 --- a/LMS.service/LMS.service.csproj +++ b/LMS.service/LMS.service.csproj @@ -10,6 +10,7 @@ + diff --git a/LMS.service/Program.cs b/LMS.service/Program.cs index 937386f..54117ee 100644 --- a/LMS.service/Program.cs +++ b/LMS.service/Program.cs @@ -1,3 +1,4 @@ +using AspNetCoreRateLimit; using Lai_server.Configuration; using LMS.DAO; using LMS.Repository.Models.DB; @@ -44,6 +45,20 @@ builder.Services.AddDbContext(options => options.UseMySql(connectionString, ServerVersion.Parse("8.0.18-mysql")); }); +// 添加内存缓存(用于存储速率限制计数器) +builder.Services.AddMemoryCache(); + +// 加载通用配置(从appsettings.json) +builder.Services.Configure(builder.Configuration.GetSection("IpRateLimiting")); + +// 注入计数器和规则存储 +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + + + builder.Services.AddIdentityCore(options => { options.SignIn.RequireConfirmedAccount = true; //已有账号才能登录 @@ -102,6 +117,9 @@ app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); +// 在管道中使用IP速率限制中间件 +app.UseIpRateLimiting(); + app.UseMiddleware(); app.UseEndpoints(endpoints => { diff --git a/LMS.service/appsettings.json b/LMS.service/appsettings.json index a9fe443..1b50098 100644 --- a/LMS.service/appsettings.json +++ b/LMS.service/appsettings.json @@ -26,6 +26,33 @@ ], "Enrich": [ "FromLogContext" ] }, - "Version": "1.0.7", + "IpRateLimiting": { + "EnableEndpointRateLimiting": true, + "StackBlockedRequests": false, + "RealIpHeader": "X-Real-IP", + "ClientIdHeader": "X-ClientId", + "HttpStatusCode": 429, + "IpWhitelist": [], + "EndpointWhitelist": [ "get:/api/status", "*:/api/health" ], + "ClientWhitelist": [ "dev-client-1", "dev-client-2" ], + "GeneralRules": [ + { + "Endpoint": "get:/lms/User/GetPublicKey", + "Period": "1m", + "Limit": 5 + }, + { + "Endpoint": "post:/lms/User/Login*", + "Period": "1m", + "Limit": 5 + }, + { + "Endpoint": "post:/lms/User/Register", + "Period": "1m", + "Limit": 10 + } + ] + }, + "Version": "1.0.8", "AllowedHosts": "*" }