AspNetCoreRateLimit .NET Core 3.0 如何基于用户Claim实现速率限制
AspNetCoreRateLimit .NET Core 3.0 认证后限速实现方案
可行性说明
完全可行。AspNetCoreRateLimit 默认的中间件注册顺序没有强绑定要求,只要把认证、授权中间件放在限速中间件之前执行,就能保证限速逻辑触发时,用户身份已经完成校验,所有Claim也已经加载完成,可以正常读取使用。
具体实现步骤
- 首先安装兼容.NET Core 3.0的NuGet包,建议选择
AspNetCoreRateLimit 3.2.2版本,4.x及以上版本仅支持.NET 5+,会出现兼容性问题。 - 自定义客户端ID解析器,替换默认从请求头取客户端ID的逻辑,改为从用户Claim中读取目标字段:
public class ClaimBasedClientIdParser : IClientIdParser { private readonly IHttpContextAccessor _httpContextAccessor; // 替换为你实际用来作为客户端ID的Claim类型 private const string TargetClaimName = "UserId"; public ClaimBasedClientIdParser(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public string ParseClientId(HttpRequest request) { var user = _httpContextAccessor.HttpContext?.User; // 未认证用户返回固定标识,可单独配置限速规则 if (user?.Identity?.IsAuthenticated != true) { return "anonymous"; } var targetClaim = user.Claims.FirstOrDefault(c => c.Type == TargetClaimName); return targetClaim?.Value ?? "anonymous"; } }
- 调整
Startup.cs中的中间件顺序,确保认证授权早于限速逻辑执行:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 异常处理、静态文件等前置中间件放在最前面 if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); // 先执行认证、授权,完成用户身份解析 app.UseAuthentication(); app.UseAuthorization(); // 再执行客户端限速逻辑 app.UseClientRateLimiting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
- 在
ConfigureServices方法中注册自定义服务和限速规则:
public void ConfigureServices(IServiceCollection services) { // 注册HttpContext访问器,用于读取当前请求的用户信息 services.AddHttpContextAccessor(); // 替换默认的客户端ID解析器为自定义实现 services.AddSingleton<IClientIdParser, ClaimBasedClientIdParser>(); // 配置客户端限速规则 services.Configure<ClientRateLimitOptions>(options => { // 全局默认规则,所有未单独配置的客户端都生效 options.GeneralRules = new List<RateLimitRule> { new RateLimitRule { Endpoint = "*", Period = "1m", Limit = 100 } }; // 针对特定Claim值的客户端配置专属规则 options.ClientRules = new Dictionary<string, List<RateLimitRule>> { // 例如Claim值为vip_001的用户,每分钟可调用1000次 { "vip_001", new List<RateLimitRule> { new RateLimitRule { Endpoint = "*", Period = "1m", Limit = 1000 } } }, // 未认证用户每分钟仅可调用10次 { "anonymous", new List<RateLimitRule> { new RateLimitRule { Endpoint = "*", Period = "1m", Limit = 10 } } } }; // 可自定义超出限速后的返回内容 options.QuotaExceededResponse = new QuotaExceededResponse { Content = "{{\"code\":429,\"msg\":\"请求过于频繁,请稍后再试\"}}", ContentType = "application/json", StatusCode = 429 }; }); // 注册限速的内存存储,分布式场景可替换为Redis存储 services.AddSingleton<IClientRateLimitCounterStore, MemoryCacheClientRateLimitCounterStore>(); services.AddSingleton<IClientRateLimitPolicyStore, MemoryCacheClientRateLimitPolicyStore>(); services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>(); // 你的其他服务注册,例如控制器、身份认证配置等 services.AddControllers(); // 此处添加你原本的JWT/Cookie等身份认证配置 }
注意事项
- 如果同时使用IP限速和客户端限速,仅需要修改客户端限速的解析逻辑即可,IP限速不受影响
- 代码中用到的目标Claim类型要和你身份认证环节写入的Claim完全一致,注意区分大小写
- 单实例场景用内存存储即可,多实例部署建议换成Redis存储,避免限速规则不统一
内容的提问来源于stack exchange,提问作者karthic4info
相关产品推荐
相关产品推荐

