AspNetCoreRateLimit icon indicating copy to clipboard operation
AspNetCoreRateLimit copied to clipboard

Using Different Rules for Different ClientIDs

Open mirdaki opened this issue 5 years ago • 4 comments

Hi all,

We are in a position where we need to apply different rules based on the type of "ClientID" we get. For example, we sometimes receive a very granular User ID, which we will set a lower rate for. Sometimes we only receive a Subscription ID (which has multiple users within it), which we will have to set a higher rate for.

Ideally we could just have something like this, though I realize that would require quite a few code changes:

{
    "Endpoint": "*",
    "IdType": "User",
    "Period": "1s",
    "Limit": 2
},
{
    "Endpoint": "*",
    "IdType": "Subscription",
    "Period": "1s",
    "Limit": 20
}

I've been looking through the code to see if there is a way to do this now, but I am having difficulty figuring out how. Is this possible with the current middleware? From what I understand creating a new RateLimitMiddleware for each type of ID could work, though I feel like that would result in a lot of duplicate code.

Any suggestions? Thank you for the feedback!

mirdaki avatar Sep 08 '20 23:09 mirdaki

You can get the rules from the user claims and the can create your own client rate limit middleware.

siddiquiAyan avatar Sep 20 '20 18:09 siddiquiAyan

Gotcha, thank you!

mirdaki avatar Sep 20 '20 19:09 mirdaki

Can someone share its own implemetations to solve this problem?

SopraniDaniele23 avatar Mar 27 '21 23:03 SopraniDaniele23

We ended up using authentication to determine if a response had a User ID or not and routing based off that:

app.UseAuthentication();
app.UseWhen(x => x.User.Identity.IsAuthenticated, builder => builder.UseCustomClientRateLimiting());
app.UseWhen(x => !x.User.Identity.IsAuthenticated, builder => builder.UseCustomIpRateLimiting());

We then use a Middleware Extension to create our implementation of RateLimitMiddleware<ClientRateLimitProcessor> and RateLimitMiddleware<IpRateLimitProcessor> to add some custom logging.

mirdaki avatar Mar 29 '21 20:03 mirdaki