You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server部署至AKS时SignalR全局消息限流防攻击方案咨询

Blazor Server SignalR 限流实现方案

Blazor Server 基于 ASP.NET Core SignalR 构建,完全支持对单连接的接收消息做限流,达到阈值后断开电路,结合 Azure SignalR Service 和 AKS 部署场景的实现步骤如下:


1. 实现自定义 SignalR 调用过滤器

通过 ASP.NET Core 原生的 IInvocationFilter 接口实现每个连接的消息计数和阈值判断,多 Pod 部署场景下使用分布式缓存统一计数:

using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Distributed;

public class RateLimitInvocationFilter : IInvocationFilter
{
    private readonly IDistributedCache _cache;
    // 可根据业务调整限流规则:示例为60秒内单连接最多允许100次消息调用
    private const int MaxAllowedRequests = 100;
    private const int RateLimitWindowSeconds = 60;

    public RateLimitInvocationFilter(IDistributedCache cache)
    {
        _cache = cache;
    }

    public async ValueTask<object> InvokeMethodAsync(InvocationContext context, Func<InvocationContext, ValueTask<object>> next)
    {
        var connectionId = context.Context.ConnectionId;
        var cacheKey = $"signalr_ratelimit_{connectionId}";

        var currentCountStr = await _cache.GetStringAsync(cacheKey);
        var currentCount = string.IsNullOrWhiteSpace(currentCountStr) ? 0 : int.Parse(currentCountStr);

        if (currentCount >= MaxAllowedRequests)
        {
            // 触发阈值直接断开当前连接
            await context.Context.AbortAsync();
            throw new InvalidOperationException("Request rate exceeded, connection closed.");
        }

        // 更新计数,设置缓存过期时间匹配限流窗口
        await _cache.SetStringAsync(
            cacheKey, 
            (currentCount + 1).ToString(), 
            new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(RateLimitWindowSeconds)
            });

        return await next(context);
    }
}

2. 注册服务与过滤器

在 Program.cs 中完成相关服务、过滤器的注册,适配 Azure SignalR 部署:

var builder = WebApplication.CreateBuilder(args);

// 注册分布式缓存,AKS场景推荐搭配Azure Redis Cache使用,保证多Pod计数统一
builder.Services.AddStackExchangeRedisCache(opt =>
{
    opt.Configuration = builder.Configuration["RedisConnectionString"];
});

// 注册自定义限流过滤器
builder.Services.AddSingleton<IInvocationFilter, RateLimitInvocationFilter>();

// 注册Blazor Server服务并注入过滤器
builder.Services.AddServerSideBlazor()
    .AddHubOptions(opt =>
    {
        opt.AddFilter<RateLimitInvocationFilter>();
        // 可选:配置单消息最大大小,降低大报文攻击风险
        opt.MaximumReceiveMessageSize = 32 * 1024;
    });

// 注册Azure SignalR服务
builder.Services.AddSignalR().AddAzureSignalR();

var app = builder.Build();

// 其他中间件配置省略...
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

3. Azure 层面兜底防护配置

可在 Azure SignalR Service 控制台直接开启内置限流规则,作为应用层限流的补充:

  • 配置单连接每秒消息数上限
  • 配置单IP最大连接数上限
  • 开启Azure门户内置的DDoS防护,拦截层7攻击流量

注意事项

  • 限流阈值需结合实际业务场景调整,避免误拦截正常用户操作,普通用户操作的消息频率一般不会超过3次/秒
  • 不可使用本地内存缓存做计数存储,否则多Pod部署场景下同个客户端的请求分散到不同Pod会导致限流规则失效
  • 可在过滤器中补充异常调用日志记录,方便后续溯源攻击行为

内容的提问来源于stack exchange,提问作者Richard Stewart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:54:01