Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/Libraries/Nop.Core/Configuration/CommonConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,11 @@ public partial class CommonConfig : IConfig
/// Default status code to set on the response when a request is rejected.
/// </summary>
public int RejectionStatusCode { get; set; } = 503;

/// <summary>
/// Gets or sets the collection of user identifiers that are exempt from rate limiting.
/// </summary>
/// <remarks>Add user IDs or IP Addresses to this collection to allow them to bypass rate limit checks. Changes to the
/// collection take effect immediately.</remarks>
public HashSet<string> RateLimitWhitelist { get; set; } = new();
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Nop.Core;
using Nop.Core.Configuration;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Security;
using Nop.Core.Http;
using Nop.Core.Infrastructure;
using Nop.Core.Security;
Expand Down Expand Up @@ -118,17 +119,32 @@ public static void ConfigureApplicationServices(this IServiceCollection services
builder.Services.AddRateLimiter(options =>
{
var settings = Singleton<AppSettings>.Instance.Get<CommonConfig>();
var securitySettings = Singleton<SecuritySettings>.Instance;

options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpContext.User.Identity?.Name ?? httpContext.Request.Headers.Host.ToString(),
{
var username = httpContext.User.Identity?.Name;
var ip = httpContext.Connection.RemoteIpAddress?.ToString();

if (settings.RateLimitWhitelist.Contains(ip) || //allow from configured IP addresses
securitySettings.AdminAreaAllowedIpAddresses.Contains(ip) || //allow from admin area allowed IP addresses
httpContext.Connection.LocalIpAddress == httpContext.Connection.RemoteIpAddress) //allow from localhost
{
return RateLimitPartition.GetNoLimiter("");
}

var partitionKey = username ?? ip ?? httpContext.Session?.Id ?? httpContext.Request.Headers.Host;

return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: partitionKey,
factory: partition => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = settings.PermitLimit,
QueueLimit = settings.QueueCount,
Window = TimeSpan.FromMinutes(1)
}));
});
});

options.RejectionStatusCode = settings.RejectionStatusCode;
});
Expand Down