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": "*" }